Anonymous user
24 game/Solve: Difference between revisions
→{{header|Tcl}}: An improved version that produces fewer poor results
(Mathematica (this was fun to write!)) |
(→{{header|Tcl}}: An improved version that produces fewer poor results) |
||
Line 459:
=={{header|Tcl}}==
This is a complete Tcl script, intended to be invoked from the command line.
<br>
<lang tcl># Encoding the various expression trees that are possible▼
{{libheader|tcllib}}
<lang tcl>package require struct::list
set patterns {
{((A x B) y C) z D}
Line 468 ⟶ 471:
}
# Encoding the various permutations of digits
set permutations [struct::list map [struct::list permutations {a b c d}] \
{apply {v {lassign $v a b c d; list A $a B $b C $c D $d}}}]
# The permitted operations
set
# Given a list of four integers (precondition not checked!) return a list of
# solutions to the 24 game using those four integers.
proc find24GameSolutions {values} {
global operations patterns permutations
set found {}
# For each possible structure with numbers at the leaves...
Line 511 ⟶ 492:
# For each possible structure with operators at the branches...
foreach x
foreach y
foreach z
set e [string map [subst {x $x y $y z $z}] $p]
# the result if it is 24
catch {
if {[expr $e] == 24.0} {
Line 532 ⟶ 514:
# Wrap the solution finder into a player
proc print24GameSolutionFor {values} {
set found [lsort -unique [find24GameSolutions $values]]
if {![llength $found]} {
puts "No solution possible"
} else {
puts "Total [llength $found] solutions (may include logical duplicates)"
puts "First solution: [lindex $found 0]"
}
Line 543 ⟶ 525:
Demonstrating it in use:
<span style="color:silver">''bash$''</span> <span style="color:brown">tclsh8.4 24player.tcl 3 2 8 9</span>
'''Total 12 solutions
'''First solution: ((9 - 3) * 8) / 2'''
<span style="color:silver">''bash$''</span> <span style="color:brown">tclsh8.4 24player.tcl 1 1 2 7</span>
'''
'''First solution: (1 + 2) * (1 + 7)'''
<span style="color:silver">''bash$''</span> <span style="color:brown">tclsh8.4 24player.tcl 1 1 1 1</span>
|