The 24s Puzzle
Appeared in Volume 8/2, May 1995
Recently my niece Lerisha showed me a mathematical game that they play at
school to improve numerical dexterity. You are given four digits in the range 1
to 9. Using each of the four digits once and the operations of addition,
subtraction, multiplication, and division (exact integer division only), you
have to form an expression that evaluates to 24. Here are some examples copied
from the game, with the supplied difficulty rating given from one star (easy)
to three star (hard).
1 2 5 6 * (1+5)*(6-2)
1 2 7 2 * 2*2*(7-1)
2 3 3 8 ** (3-2)*(3*8)
4 6 9 5 ** 4+6+(9+5)
7 3 8 3 ** 7+8+3*3
7 3 1 6 ** (7-3)*(1*6)
4 8 7 4 *** 4-8+7*4
7 2 4 9 *** 7+9+2*4
2 3 8 9 *** 8//2*(9-3)
3 4 8 1 *** (3-1)*(4+8)
The children I played with were surprisingly quick at forming an appropriate
expression, and some simple heuristics were clearly noticable. I've written a
dumb Prolog program to create these expressions, appended below. It's a fun
challenge to write a better one that captures some of the obvious heuristics.
go(Numbers):-
select(N1,Numbers,Numbers1),
select(N2,Numbers1,Numbers2),
select(N3,Numbers2,[N4]),
(0 is N1 mod N2 ->
member(Op1,[*,//,+,-]);
member(Op1,[*,+,-])),
Exp1 =.. [Op1,N1,N2],
(0 is N3 mod N4 ->
member(Op2,[*,//,+,-]);
member(Op2,[*,+,-])),
Exp2 =.. [Op2,N3,N4],
(Exp2 > 0 ->
member(Op3,[*,//,+,-]);
member(Op3,[*,+,-])),
Exp3 =.. [Op3,Exp1,Exp2],
Value is Exp3,
write(Exp3),write(' '),write(Value),nl,
Value == 24.
Geoff Sutcliffe
geoff@cs.jcu.edu.au