0

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:

  1. Only using parentheses when needed (by tracking precedence and associativity).
  2. Ordering operands for easy comparisons.
Alex O
  • 1,429
  • 2
  • 13
  • 20

1 Answers1

1

After you generated all the possible expressions that result in 24, I would add a normalization step. The goal of this step is to remove redundant parenthesis.

A nice explanation of how to remove redundant parenthesis is given here. After that you just have a set of all your normalized expressions.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • This is a start, but you need more normalisation -- e.g. presumably you want to consider `2 + 4 + 9 + 9` to be the same as `4 + 9 + 2 + 9` and so on. You can do this by picking an order for all operands to associative and commutative operators like `+` and `*` (e.g. smallest first). – j_random_hacker May 31 '16 at 15:33
  • 1
    @j_random_hacker Yes, you are right. Thank you, I forgot about that. And yes, it can be solved by sorting operands inside of a group of commutative operators. You also forgot about minus. `(a -b -c)`. Minus can be treated like +: `a + (-b) + (-c)` and sorting -b and -c. – Salvador Dali May 31 '16 at 18:52