Skip to content

Instantly share code, notes, and snippets.

@mattdodge
Created July 19, 2013 23:18
Show Gist options
  • Save mattdodge/6043056 to your computer and use it in GitHub Desktop.
Save mattdodge/6043056 to your computer and use it in GitHub Desktop.
Solve the game 24 for any solution target and any numbers n = The target number (e.g. 24) nums = Array of numbers (floating point ok) to use solveStr = A helper string for this recursive method that returns a formula This method will return the first (not exhaustive!) possible solution to the game, or False if none exists Example: For the 24 gam…
def solve(n, nums, solveStr='x'):
''' Solve the game 24 for any solution target and any numbers
n = The target number (e.g. 24)
nums = Array of numbers (floating point ok) to use
solveStr = A helper string for this recursive method that returns a formula
This method will return the first (not exhaustive!) possible solution to the game, or False if none exists
Example: For the 24 game 1,3,4,6 call it the following way:
solve(24, [1,3,4,6])
> (6/(1-(3/4)))
'''
n = float(n)
if len(nums) == 1:
if n == float(nums[0]):
return solveStr.replace('x', str(int(n)))
else:
return False
solved = False
for num in nums:
num = float(num)
possibles = [
( n-num , '+', False),
( num-n , '-', True),
( n+num , '-', False),
( n*num , '/', False),
( (n/num if num != 0 else 100000) , '*', True),
( (num/n if n != 0 else 100000) , '/', True)
]
wo = [x for x in nums]
wo.remove(num)
for possible in possibles:
if possible[2]:
nextStr = solveStr.replace('x', '(' + str(int(num)) + possible[1] + 'x)')
else:
nextStr = solveStr.replace('x', '(x' + possible[1] + str(int(num)) + ')')
solved = solved or solve(possible[0], wo, nextStr)
return solved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment