1

例如,我有表达式x+2*(4*7)的标记数组:

{ "x" , "+" , "2" , "*" , "(" , "4" , "*" , "7" , ")" }

我需要像x+56这样的输出。这是一个简单的例子,但可能要困难得多。我知道 Dijkstra 的调车场算法,但不确定这是否可以专门帮助优化。坦率地说,我不知道如何理解最大优化的表达式,因为我看不到所有可能的优化方法。也许有一种算法可以考虑所有细微差别?

4

2 回答 2

3

在您的问题中,用于优化表达式的技术称为常量折叠。它查找每个值都是常量的表达式,并将该表达式替换为运算结果。

Start with x+2*(4*7)
Notice 4*7 is an operation with constant arguments
Compute 4*7=28, replace in expression to get x+2*(28)
Notice (28) can be de-bracketed, to get x+2*28
Notice 2*28 is an operation with constant arguments
Compute 2*28=56, replace in expression to get x+56
Notice there are no more operations with all constant arguments
End with x+56

也可以看看:

于 2013-05-12T01:25:31.970 回答
1

您可能正在寻找的是计算机代数系统。有几个可用的开源系统;如果您将使用限制为每月几千次 API 调用,您也可以免费使用Wolfram Alpha API 。

于 2013-05-12T01:24:55.287 回答