There is a card game here in China, use a standard 52 card deck of cards. Draw four cards and use any elementary operators $(+,-,\times, \div)$, and only use each card value once to get a result of 24.
The cards start with Ace = 1 to King = 13.
example: The four cards are 5,5,5,1. $\left(5-\left(1\div 5\right)\right)\times 5=24$
Is there some method other than brute force to find a solution for solvable solutions? I am asking because I don't think anyone has the time to do every combination.
I don't know of any method to solve this other than brute force, but the computer is really good at solving things by brute force, so I got the computer to do it.
The program's main data structure is a series of hash tables stored in
$seen[1],$seen[2],$seen[3],$seen[4]. Each table maps numeric values to lists of expressions that represent that value.$seen[i]contains expressions with i leaves.$seen[1]is manually initialized. Then the functionscan_seenis run to scan over every pair of expressions in$seen[1]. Each pair is assembled into a larger expression and inserted under the correct key in$seen[2]. Then more scans are done, until `$seen[4] is completely populated. At this point it contains every possible expression with four leaves, grouped by expression value.The definitions of the operators are in the
%optable. An operator is allowed to return an undefined value to indicate that no expression should be retained in@seen. For example, the division operator does this when the divisor is zero. But also multiplication and addition do this when the second argument exceeds the first; this prevents the program from indexing both $a+b$ and $b+a$.Because every operator is considered to require exactly two arguments, the program distinguishes the expressions $a + (b +c)$ from $(a+b)+c$. Also the hack for eliminating commutators doesn't help the program realize that $a + (b+c)$ is the same as $b + (a + c)$. A lot of improvements could be put into the code to eliminate solutions that are too similar to other solutions.
Once every possible expression with four leaves is indexed, we just emit all the expressions in
$seen[4]{24}, which is the ones whose value is 24. The complete output is here. I sorted the output expressions, which the program itself doesn't do.It would be more effective to have the program emit all the solutions for all values, with solutions for each value into a different file, since at this point it has them all prepared; changing the program to do that is easy.
Complete code is here. Perl is good for this kind of programming because it runs reasonably quickly, and you don't waste a lot of time on implementing the data structures or doing memory management.
[ Addendum 2017-09-18: I wrote a series of articles about various aspects of this puzzle: (1) (2) (3) ]