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 |
|||
⚫ | |||
# solutions to the 24 game using those four integers. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
# 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} { |
||
lappend found [string map {.0 {}} $e] |
|||
if {$stopAtFirst} return |
|||
incr found |
|||
} |
} |
||
} |
} |
||
Line 248: | Line 247: | ||
} |
} |
||
} |
} |
||
return $found |
|||
} |
|||
⚫ | |||
# Wrap the solution finder into a player |
|||
proc print24GameSolutionFor {values} { |
|||
set found [find24GameSolutions $values] |
|||
if {![llength $found]} { |
|||
⚫ | |||
} else { |
} else { |
||
puts "$found solutions |
puts "Total [llength $found] solutions (may include duplicates)" |
||
puts "First solution: [lindex $found 0]" |
|||
} |
} |
||
} |
} |
||
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) |
First solution: (1 + 2) * (1 + 7) |
||
$ tclsh8.4 24player.tcl 1 1 1 1 |
|||
No solution possible</pre> |