# 24 Math Game Algorithm?

Object of the game: Given 4 positive integer numbers, perform elementary operations on the 4 numbers so that the result gives you 24. i.e. given 9,6,5,3 a correct way to yield 24 is (6-3)*5+9 = 24 Note: Some 4 numbers may have multiple solutions while others may have no solutions such as 1,1,1,1. Also, you may only use each number once! The elementary operations that are allowed to be used are x,/,+,-,()

I was looking to write a program in order to compute the solution if it exists given 4 positive integer numbers. As of right now the only thing my mind is pointing me towards is using a brute force style of method to compute the solution. Wanted to know if you guys had any solutions

Any advice would be much appreciated!

• Do you mean that you can only use each number once, or do you really mean operation? – bill s Dec 9 '17 at 19:54
• You can only use each number once, you can use the same operation multiple times – Yaseen Ayuby Dec 9 '17 at 20:39
• I saw something similar solved using genetic algorithms – Raffaele Dec 9 '17 at 20:54
• try every combination by brute force. I guess there would not be many combinations. – Harry Dec 10 '17 at 8:32
• Wolfram Demonstrations Project:demonstrations.wolfram.com/KryptoOr24Game – Harry Dec 10 '17 at 8:37

try all possible combinations (4*3*2*1*4^3=1536)

ops = {"+", "-", "*", "/"};
allops[x_] :=
Flatten@Outer[{"((" <> x[[1]] <> #1 <> x[[2]] <> ")" <> #2 <>
x[[3]] <> ")" <> #3 <> x[[4]]} &, ops, ops, ops];
select24[x_] :=
Select[{#, ToExpression@#} & /@ Flatten[allops /@ Permutations[ToString /@ x]], #[[2]] == 24 &]


now

select24[{6, 4, 2, 1}]


gives

{{"((2-1)*6)*4", 24}, {"((2-1)*4)*6", 24}}