Lenny Domnitser’s

⇙ Jump to content


This is a static archive of the domnit.org blog,
which Lenny Domnitser wrote between 2006 and 2009.

Solving 24

24 is a fun arithmetic game, if arithmetic games are fun.

Choose four numbers between 1 and 9. Make 24 out of them, using addition, subtraction, multiplication, and division, using each number once. For example, (2, 4, 7, 7) is (7+7)*2-4.

Another fun problem is to solve the entire game. The 403 404 solvable problems have 33,483 33,531 solutions [1], treating every possible grouping and order as distinct (((1+2)+3), (1+(2+3)), and ((2+1)+3) are all considered different expressions. So are (1+1) and (1+1) from a problem set containing two 1s.).

#!/usr/bin/env python
import solve24
for a in xrange(1, 10):
    for b in xrange(a, 10):
        for c in xrange(b, 10):
            for d in xrange(c, 10):
                if solve24.is_possible(a, b, c, d):
                    f = open('24/%s%s%s%s.txt' % (a, b, c, d), 'w')
                    for solution in solve24.solve(a, b, c, d):
                        print >> f, solution

produces a directory of all the solutions.

The solve24 module can do more than solve 24. The _solver in the code is pretty flexible, and can be adapted to produce possible expressions from pretty much any operators and numbers.

Closing problem: 1, 4, 5, 6. (This is extremely difficult.)

Update: Computers suck. Fixed.