Skip to content

Instantly share code, notes, and snippets.

@vivus-ignis
Created March 13, 2012 00:04
Show Gist options
  • Save vivus-ignis/2025569 to your computer and use it in GitHub Desktop.
Save vivus-ignis/2025569 to your computer and use it in GitHub Desktop.
#!/usr/bin/env tclsh
set coins_pile $::argv
proc take_left {} {
global coins_pile
set taken [lindex $coins_pile 0]
set coins_pile [lreplace $coins_pile 0 0]
return $taken
}
proc take_right {} {
global coins_pile
set taken [lindex $coins_pile end]
set coins_pile [lreplace $coins_pile end end]
return $taken
}
proc take_best_coin {} {
global coins_pile
set left_half [lrange $coins_pile 0 [expr [llength $coins_pile] / 2 - 1] ]
set right_half [lrange $coins_pile [expr [llength $coins_pile] / 2] end]
# puts "LH: $left_half"
# puts "RH: $right_half"
set left_sum 0
foreach coin $left_half { set left_sum [expr $left_sum + $coin] }
set right_sum 0
foreach coin $right_half { set right_sum [expr $right_sum + $coin] }
# if { [lindex $coins_pile end] > [lindex $coins_pile 0] } {}
if { $right_sum > $left_sum } {
return [take_right]
} else {
return [take_left]
}
}
if { [ expr [llength $coins_pile] % 2 ] != 0 } {
puts "Amount of coins is not even, exiting"
exit 1
}
set property(me) {}
set property(partner) {}
while { [llength $coins_pile] > 0 } {
foreach player {me partner} {
lappend property($player) [take_best_coin]
}
}
puts "My coins are: $property(me)"
puts "Partners' coins are: $property(partner)"
set sum 0
foreach coin $property(me) { set sum [expr $sum + $coin] }
puts "I won: $sum"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment