从定义为字符串的运算符执行算术运算

时间:2016-06-24 06:57:43

标签: java algorithm operators

我最近一直试图找到解决这个问题的方法,但到目前为止我一直没有成功。

我正在考虑进行操作a # b # c # d,其中a,b,c和d是预定义的常量,#可以取以下任何运算符'+',' - ','*'的值,'/'。

我正在考虑为#{1}}找到a # b # c # d的所有可能(不同)解决方案。#/ p>

我在考虑以下几行的逻辑:

// 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()是一个函数,它只检查获得的新解决方案是否与获得的所有先前解决方案不同。

我还没有找到在操作数之间应用运算符的方法。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

从JDK1.6开始,您可以使用内置的Javascript引擎为您评估此表达式。

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));
    } 
}

因此,您可以根据运算符优先级规则使用它来计算表达式。

此外,如果您只需要解决方案的数量,可能更容易使用TreeSet,然后在最后打印集合的大小。

以下是完整的解释:

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);
        }
    }
}
相关问题