24 game/Solve: Difference between revisions

Content added Content deleted
m (Added another sample (inspired by talk page))
(→‎{{header|Tcl}}: Revise for better separation between solver and player, with nicer output)
Line 214: Line 214:
{A d B a C b D c}
{A d B a C b D c}
}
}
set stopAtFirst 1


# Given a list of four integers (precondition not checked!) return a list of
proc findSolution {values} {
# solutions to the 24 game using those four integers.
global patterns permutations stopAtFirst
proc find24GameSolutions {values} {
set found 0
global patterns permutations
set found {}
# For each possible structure with numbers at the leaves...
# For each possible structure with numbers at the leaves...
foreach pattern $patterns {
foreach pattern $patterns {
Line 238: Line 239:
catch {
catch {
if {[expr $e] == 24.0} {
if {[expr $e] == 24.0} {
puts [string map {.0 {}} $e]
lappend found [string map {.0 {}} $e]
if {$stopAtFirst} return
incr found
}
}
}
}
Line 248: Line 247:
}
}
}
}
if {!$found} {
return $found
}
puts "no solution possible"

# Wrap the solution finder into a player
proc print24GameSolutionFor {values} {
set found [find24GameSolutions $values]
if {![llength $found]} {
puts "No solution possible"
} else {
} else {
puts "$found solutions total (may include duplicates)"
puts "Total [llength $found] solutions (may include duplicates)"
puts "First solution: [lindex $found 0]"
}
}
}
}
findSolution $argv</lang>
print24GameSolutionFor $argv</lang>
Demonstrating it in use:
Demonstrating it in use:
<pre>$ tclsh8.4 24player.tcl 3 2 8 9
<pre>$ tclsh8.4 24player.tcl 3 2 8 9
12 solutions total (may include duplicates)
((9 - 3) * 8) / 2
First solution: ((9 - 3) * 8) / 2
$ tclsh8.4 24player.tcl 1 1 2 7
$ tclsh8.4 24player.tcl 1 1 2 7
16 solutions total (may include duplicates)
(1 + 2) * (1 + 7)</pre>
First solution: (1 + 2) * (1 + 7)
$ tclsh8.4 24player.tcl 1 1 1 1
No solution possible</pre>