#!/usr/bin/env tclsh8.6 gets stdin line set calls [split $line ,] gets stdin line set b {} set boards {} while {[gets stdin line] >= 0} { if {$line eq ""} { lappend boards $b set b {} } lappend b {*}[regexp -all -inline {\S+} $line] } lappend boards $b # Iterate over boards. Keep track of the score and number of turns # to victory for the board with the shortest path to victory. set min 99999 set minscore 0 foreach b $boards { # Set up board as an array for easy crossing-off. array unset board; array unset spot foreach i {0 1 2 3 4} { foreach j {0 1 2 3 4} { set t [expr {$i*5 + $j}] set board($i,$j) [lindex $b $t] set spot([lindex $b $t]) [list $i $j] } } set turns 0 foreach num $calls { incr turns if {! [info exists spot($num)]} continue lassign $spot($num) ii jj set board($ii,$jj) X # Winner? Check currently marked row and column. set winner 1 foreach i {0 1 2 3 4} { if {$board($i,$jj) ne "X"} {set winner 0; break} } if {$winner} break set winner 1 foreach j {0 1 2 3 4} { if {$board($ii,$j) ne "X"} {set winner 0; break} } if {$winner} break } # If we won, calculate the score. num has the last number called. # But don't bother if we took too long. if {! $winner} continue if {$turns >= $min} continue set score 0 # puts "Winner at turns=$turns:" foreach i {0 1 2 3 4} { foreach j {0 1 2 3 4} { if {$board($i,$j) ne "X"} {incr score $board($i,$j)} # puts -nonewline [format %-3s $board($i,$j)] } # puts "" } set score [expr {$score * $num}] # puts "score=$score" set min $turns set minscore $score } puts $minscore