Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 

Repository files navigation

TwentyFour Solver

A recursive backtracking solver for a generalized version of the Game of 24.

Usage

print(solve_24([1, 2, 3, 4]))   # Output: (1 + 2 + 3) * 4
print(solve_24([3, 3, 8, 8]))   # Output: 8 / (3 - (8 / 3))
print(solve_24([1, 5, 5, 5]))   # Output: 5 * (5 - (1 / 5))
print(solve_24([5, 6, 7, 8]))   # Output: (5 + 7) * (8 - 6)

Algorithm

The solver finds solutions by repeatedly shrinking the list of numbers step-by-step:

  1. Pick any 2 numbers from the list.
  2. Combine them using an operation (+, -, *, /) to create a single, parenthesized expression (for example, 3 and 8 combine into (8 / 3)).
  3. Put the result back in the list, replacing the two original numbers.
  4. Repeat this process recursively until only 1 final number remains.
  • Success: If the final remaining number equals the target, the algorithm returns the built-up math string.
  • Safety: If a combination requires dividing by zero, the solver immediately skips it and tries a different path.

© Copyright 2026 Blake Rayvid. All rights reserved.