Categories
Development

Expression evaluation

I had to implement a library which evaluates a set of mathematical expressions with variables, where each variable can also be an expression. Luckily we had JGraphT library already on the class path, so it was quite quick and painless. All that is needed is:

  • Parse all expressions, extract variables
  • Build a directed graph, expression is a node and edge represents a dependency of an expression on other expression/variable.
  • Check that it does not contain cycle.
  • Create a DepthFirstIterator and gradually calculate all expression values and collect them in a map. This ensures that all variable values are available when an expression is evaluated.

Code can be found here:

https://github.com/MavoCz/GraphExpressionEvaluator

Example of an expression tree as created by JGraphT visualisation: