#!/usr/bin/env tclsh9.0 namespace import ::tcl::mathop::+ proc input {} { global grid rows cols gr gc set grid [list] set rows 0 set gr -1; set gc -1 while {[gets stdin line] >= 0} { if {$line eq ""} continue set cols [string length $line] lappend grid [split $line ""] if {$gr == -1} { set gc [string first ^ $line] if {$gc > -1} {set gr $rows} } incr rows } } proc guard {} { global grid rows cols gr gc set face 0 ;# 0=N 1=E 2=S 3=W array set facing {0 {-1 0} 1 {0 1} 2 {1 0} 3 {0 -1}} lset grid $gr $gc X set r $gr; set c $gc # set step 0 while 1 { lassign $facing($face) dr dc set r2 [+ $r $dr] if {$r2 < 0 || $r2 >= $rows} break set c2 [+ $c $dc] if {$c2 < 0 || $c2 >= $cols} break if {[lindex $grid $r2 $c2] eq "#"} { set face [expr {($face + 1) % 4}] continue } # puts "r=<$r> c=<$c>" set r $r2; set c $c2 lset grid $r $c X # incr step # if {[expr {$step % 10}] == 0} show } } proc count {} { global grid rows cols gr gc set n 0 for {set r 0} {$r < $rows} {incr r} { for {set c 0} {$c < $cols} {incr c} { if {[lindex $grid $r $c] eq "X"} {incr n} } } puts $n } proc show {} { global grid rows cols for {set r 0} {$r < $rows} {incr r} { for {set c 0} {$c < $cols} {incr c} { puts -nonewline "[lindex $grid $r $c] " } puts "" } } input # show guard count