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.
2
  • Do you mean your algorithm may work at the same time with infix, postfix or polish notation? Commented May 31, 2016 at 0:09
  • No, I mean figure out whether two arithmetic expressions are equivalent, and I don't care what notation it works with Commented May 31, 2016 at 2:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.