24 game/Solve: Difference between revisions

→‎{{header|Tcl}}: add some comments
(→‎Tcl: Added implementation)
(→‎{{header|Tcl}}: add some comments)
Line 165:
=={{header|Tcl}}==
This is a complete Tcl script, intended to be invoked from the command line.
<lang tcl># Encoding the various expression trees that are possible
<lang tcl>set patterns {
{((A x B) y C) z D}
{(A x (B y C)) z D}
Line 172 ⟶ 173:
{A x (B y (C z D))}
}
# Encoding the various permutations of digits
set permutations {
{A a B b C c D d}
Line 202 ⟶ 204:
global patterns permutations
set found 0
# For each possible structure with numbers at the leaves...
foreach pattern $patterns {
foreach permutation $permutations {
Line 210 ⟶ 213:
d [lindex $values 3].0
}] [string map $permutation $pattern]]
 
# 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]
 
# Try to evaluate (div-zero is an issue!) and print if it is 24
catch {
if {[expr $e] == 24.0} {
Anonymous user