### Preword

Because I am going to teach at a coding summer camp to middle school kids in Changsha very soon. I have been searching for interesting projects for them to build so they can learn better. And this idea of building a solver for the 24 Game cross my mind. It is rather interesting and takes me actually a lot longer than I expect to finish it. Probably won’t give this to them; maybe as a optional challenge.

### What is the 24 Game?

It is basically a Card game. It originates in China sometime last century.

This Chinese game requires skill at mental arithmetic. It has been played in Shanghai at least since the 1960’s and may have originated there, and it is also known in some other cities, for example in Qingdao and Guangzhou. Since the end of the 20th century it has also spread to some places in North America. The basic game for two players will be described first, followed by variations for a larger number of players and extra options.

Basically you are given a deck of poker cards and the Jokers are removed. You treat A~10 as 1~10 and J~K as 11~13, (in early versions only A~10 is included) and you have to do some calculations to the four card so the result equals 24. Only basic arithmetics are allowed (+, -, *, / and ( )) and each number can only be used once. For example if the four cards were 2, 3, 6, 9 then possible solutions would be (9+6-3)×2=24, (9-3)×(6-2)=24 or (9×3)-(6÷2)=24. Whoever can tell a correct equation first wins the round.

### The Algorithm

Was thinking of a iterative approach but code will be too ugly to read. Decide to do a recursive approach. Basically the thinking is to reduce the amount of numbers to calculate to two, so if the output equals 24 it is valid. Take 2 numbers each time and do the 4 operations to reduce to one number and eventually there will be only 2 numbers remaining. Theoretically, this should apply to any amount of numbers and any output to be calculated.

For example:

1. There are 4 numbers, take 2 of them and do some calculations so there will be 3 numbers remaining.
2. Now there are 3 numbers, do whatever operations so there will be only 2 numbers remaining.
3. If the 2 can get the output of 24, it is a valid equation; otherwise it is false.

### Sample Output

• 4 Numbers

• More than 4 Numbers

### Reference

Rules of Twenty Four