【问题标题】:Perform arithmetic operations from operators defined as strings从定义为字符串的运算符执行算术运算
【发布时间】:2016-06-24 06:57:43
【问题描述】:

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

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

我正在考虑为 # 中的所有运算符替换找到 a # b # c # d 的所有可能(不同)解决方案。

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

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

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

非常感谢您对此的任何帮助。

【问题讨论】:

  • 你的实现会忽略操作的优先级,如果a + b * c,它会先计算b * c吗?
  • 我更喜欢操作优先的实现。但现在没有它也行。
  • 你能贴出 isNew 函数的代码吗?我不认为它在做它应该做的事情
  • 看看stackoverflow.com/a/37712870/1090562 可能会给你一些想法。
  • 嗯,在我的情况下它并不明显,因为结果不明显(总是 8)。但我明白,你的意思。但是,我认为您必须编写一个小解析器和计算器。

标签: java algorithm operators


【解决方案1】:

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

【讨论】:

  • 感谢@Ahmed,这确实让我在遵循运算符优先级的同时评估表达式。
猜你喜欢
  • 2017-01-10
  • 2013-09-06
  • 1970-01-01
  • 2013-02-19
  • 2019-03-24
  • 2014-02-17
  • 2016-08-16
  • 1970-01-01
相关资源
最近更新 更多