How to program a way to create mathematics formulas

algorithmsmath

For one of my project ideas, I want to create a dice rolling app. It would allow people to setup somewhat complex combinations of dice roll cascades in a visual way.

I have a pretty good idea on how I would program the logic for the dice, namely as if you're creating a math formula;

Class:

Formula

Properties:

Left formula
Right formula
Function

Thus, adding X = A + B would consist of Formula X, with left Formula A, right Formula B and function Add. Formula A and B would consist of left a or b, right null and function Constant.

This approach seems fine to me, but I like to try and find approaches others have come up with. However, because 'programming math' tends to lead to completely different questions (of the 'Do I need to learn math to program' or 'How do I program this formula' variety), I'm having difficulties finding other approaches.

Best Answer

One way to do this is to convert your math / dice expression to Reverse Polish Notation (postfix). Once converted, the expression is fairly easy to evaluate.

To do the conversion, you can use the Shunting Yard Algorithm. This can handle not only basic operators, but also nested expressions and function calls.

The only area you would have to extend is handling the nD dice notation. So instead of 5 + 5, you'd be interpreting 5d6 + 5d6. That should be easy enough to handle once you have the expression reduced to tokens.

An expression evaluator like this is a very good learning project.

Related Topic