aditya aditya - 5 months ago 14
Java Question

Perform arithmetic operations from operators defined as strings

I have been recently trying to find a solution to this problem, but so far I have been unsuccessful.

I was thinking of doing the operation

a # b # c # d
, where a, b, c and d are predefined constants and # can take the value of any of the following operators '+', '-', '*', '/'.

I was thinking of finding all possible (distinct) solutions of
a # b # c # d
for all the operators replacement in #.

I was thinking of a logic on the following lines:

// Global declaration of an array list
static ArrayList<Double> values;

String[] chars = {"+", "-", "*", "/"};
int totalSolutions = 0;
values = new ArrayList<Integer>();
for (int i=0; i<chars.length; i++){
for (int j=0; j<chars.length; j++){
for (int k=0; k<chars.length; k++){
if (isNew(a chars[i] b chars[j] c chars[k] d)) totalSolutions += 1;
}
}
}
public static boolean isNew(double value){
if (values.contains(value)) return false;
else values.add(value);
return true;
}


isNew() is a function which just checks if the new solution obtained is different from all the previous solutions obtained.

I have not found out ways of applying the operator between the operands.

Any help on this is greatly appreciated.

Answer

Starting from JDK1.6 you can use built-in Javascript engine to evaluate this expression for you .

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Main {
  public static void main(String[] args) throws Exception{
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    String expression = "100+200/100*2";
    System.out.println(engine.eval(expression));
    } 
}

So you can use it to calculate the expression according to operators precedence rules.

Also If you need just the count of solutions , it might be easier to use TreeSet then print the size of the set at the end.

Here is a full explanation :

public class Main {

    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        int a = 100;
        int b = 200;
        int c = 300;
        int d = 100;
        String[] chars = {"+", "-", "*", "/"};
        try {
            TreeSet<String> set = new TreeSet<>();
        for (int i=0; i<chars.length; i++){
           for (int j=0; j<chars.length; j++){
                for (int k=0; k<chars.length; k++){
                    String expression = a+chars[i]+b+chars[j]+c+chars[k]+d;
                         set.add(String.valueOf(engine.eval(expression)));
                }
            }
        }
            System.out.println(set.size());
        } catch (ScriptException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
Comments