Shunting Yard Algorithm with Variables

▼魔方 西西 提交于 2020-08-04 18:24:08

问题


I'm currently working on a modified version of the Shunting Yard Algorithm that would work with variables, but I cant figure out how to get it to work. For example, I would want the algorithm to re-write 2 * (2x + 5) - 5 to 4x + 5. Any ideas / links to already implemented algorithms that does this already?


回答1:


  1. Take the expression: 2 * (2x + 5) - 5
  2. Add the * symbol to make it more understandable for the computer: 2 * (2*x + 5) - 5
  3. Parse it using the Shunting Yard Algorithm, it becomes: 2 2 x * 5 + * 5 - (Each character could be seen as an element of an array).
  4. With the parsed expression, create the binary tree:

- / \ * 5 / \ 2 + / \ * 5 / \ 2 x 5. Define and apply algebraic rules to the tree. For example, a rule to be able to 'multiply' the 2 node with the 2 * x + 5 subtree.



来源:https://stackoverflow.com/questions/25320505/shunting-yard-algorithm-with-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!