Given two arithmetic expressions e1 and e2 that have same four operands, judge if they are equivalent. Two expression are equivalent if they can be arranged to be the same expression according to mathematical properties. Return true if they are equivalent, otherwise false.
I just cannot figure out an algorithm to solve this problem. I need this algorithm to solve the problem to list all solutions without replication of 24 Game.
Examples
Example 1:
- Input: e1 is "6 * (2 + 5 - 3)", e2 is "(5 - 3 + 2) * 6".
- Output: true
Example 2:
- Input: e1 is "5 - (2 - 7 * 3)", e2 is "3 * 7 + 5 - 3".
- Output: true
Example 3:
- Input: e1 is "(7 + 5) / (2 / 4)", e2 is "(7 + 5) * 4 / 2".
- Output: true
Example 4:
- Input: e1 is "(7 + 5) * 4 / 2", e2 is "(7 + 5) * (4 - 2)".
- Output: false.
Constraints
- e1 and e2 have exactly the same four integer number as operands that is between 1 to 10.
- Only four basic binary arithmetic operation can be used:
addition(+), subtraction(-), multiplication(*), division(/). - Minus(-) can only be used as a subtraction operator and not as a unary operator to compute the numeric negation of its operand.
- Parentheses can be used.
Finding an algorithm to solve this is challenging, since a special case of the problem as you've presented it is determining whether to polynomials are equivalent.
Polynomial identity testing has unknown computational complexity, but it's known that brute force solutions can take exponential time. Therefore, the standard approach to this is to use randomized inputs and test for equality using the Schwartz-Zippel lemma.
I expect that writing an implementation of this will be easier than other approaches and have better performance.
Note that you need to be careful of both integer overflow and floating-point issues in implementing this. For your case, it's probably sufficient to use unsigned 64-bit integers or long doubles.
You may worry about the probabilistic nature of the algorithm. But consider that we can transfer the question of whether
p=qinto the question of whetherp-q=0. Ifp-qis zero across its entire range, thenp=q. Otherwise,p-qis ad-degree polynomial with at mostdpoints where it equals zero. If we choose test values from a setSof size|S|then the probability of finding one of these points isd/|S|, which becomes small as|S|grows. If we make multiple evaluations we can drive the probability even lower.