For fun I am playing around with a program to solve the 24 game, and I'm trying to find a way to avoid displaying equivalent expressions when checking for multiple solutions.
For example, given the numbers 6, 6, 6, 6
, the algorithm may (iteratively or recursively) generate several equivalent expressions.
For example: ((6 + 6) + 6) + 6
, (6 + 6) + (6 + 6)
and others, since all of them mean "add the four sixes together".
Obviously, things become more interesting when dealing with all four arithmetic operands.
For example, the expressions A * B + C * D
and C * D + B * A
are also equivalent.
Another case, which may be more difficult to detect is A - B - C - D
vs A - (C + B + D)
Ideas that I have so far:
- Only using parentheses when needed (by tracking precedence and associativity).
- Ordering operands for easy comparisons.