我将如何评估某个公式?
我有一个多维数组列表,我向用户询问一个公式,然后我对其进行评估。问题是我得到这样的用户输入:
((a1+a2)/12)*a3
问题是 a1 、 a2 和 a3 引用列,我必须将其评估为某个值,我完全不知道如何解决这个问题任何建议或指导会很棒的。此外,每次任何列中的值更新时,该计算值都必须更新。问题是公式不是硬编码的。
I have a multidimension arrayList and I ask the user for a formula and than I evaluate it. The problem is that I get user input like this:
((a1+a2)/12)*a3
the problem is that a1 and a2 and a3 refer to columns and I have to evaluate it to a certain value to it and I am totally lost on how to approach this problem any advice or guidance would be great. Also this calculate value has to update every time the value in any of the columns Update. The thing is the formula isn't hard coded.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种可能性是编写一种解析器。最好使用 二叉树 结构来表示表达式,而不是列表。
每个非叶节点都是一个操作,每个叶节点都是操作数。
A possibility is write a sort of parser. It's better to use a binary tree structure to represent an expression, rather than a list.
Each non-leaf node is an operation and every leaf is operand.
就我个人而言,我会尽力避免所有解析内容,并寻找一个允许您使用自己的变量解析器的 EL 库。然后您需要做的就是将变量连接到您的支持模型。 (在您的情况下,在单词/字母边界上进行分割,并查找单元格内容。)
这还允许您通过简单地将任意函数暴露给 EL 引擎来包含它们。 OGNL、MVEL 等可能是一个很好的起点。看起来容易多了。
Personally, I'd try really hard to avoid all the parsing stuff, and look for an EL library that allows you to use your own variable resolver. All you'd need to do then is hook up the variables to your backing model. (In your case, splitting on word/letter boundary, and looking up cell contents.)
This would also allow you to include arbitrary functions by simply exposing them to the EL engine. Something like OGNL, MVEL, etc. might be a good starting point. Seems much easier.
Heisenbug 的建议的替代方法是尝试 Dijkstra 的 < a href="http://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="nofollow noreferrer">调车场算法。您不依赖树结构,而是使用堆栈和队列。优点是涉及的这些数据结构并不是非常复杂。缺点是,实现算法时的任何错误都可能很容易被忽略,因为您需要彻底了解所涉及的操作才能知道您的实现是否正确。
An alternative to Heisenbug's suggestion is to try Dijkstra's shunting-yard algorithm. Instead of relying on a tree structure, you use stacks and queues. The advantage is that these data structures involved are not terribly complicated. The downside is that any errors in implementing the algorithm could be easily missed, as you need to thoroughly understand the operations involved to know if your implementation is correct.
您需要将公式转换为二进制表达式树之类的东西。这应该不那么困难。
然后,您将需要遍历这棵树,以在开始时以及每次 arrayList 中的值发生变化时计算表达式值。首先集中精力构建树并在评估它时获得正确的值。不要忘记负数和变量!之后观察 arrayList 的变化应该是微不足道的。
You will need to turn the formula into something like a Binary Expression Tree. This should be not that difficult.
Then you will need to traverse this tree to evaluate the expression value at the start and each time a value in the arrayList changes. Concentrate first on building the tree and getting correct values when you evaluate it. Don't forget negative numbers and variables! Watching the arrayList for changes should be trivial after that.