#!/usr/bin/env tclsh9.0 namespace import ::tcl::mathop::* set rows 103 set cols 101 if {[llength $argv] == 2} {lassign $argv rows cols} proc input {} { global rows cols robots set ends [list] set re {p=(-?\d+),(-?\d+) v=(-?\d+),(-?\d+)} while {[gets stdin line] >= 0} { if {$line eq ""} continue if {! [regexp $re $line -> pc pr vc vr]} continue lappend robots [list $pr $pc $vr $vc] } } proc search {} { global rows cols robots set row [list] for {set c 0} {$c < $cols} {incr c} {lappend row 0} set grid [list] for {set r 0} {$r < $rows} {incr r} {lappend grid $row} set turn 1 while {$turn < 1000000} { # Clear the grid (unless it's turn 1). if {$turn > 1} { for {set r 0} {$r < $rows} {incr r} { for {set c 0} {$c < $cols} {incr c} { lset grid $r $c 0 } } } # Put the robots in the grid. foreach robot $robots { lassign $robot pr pc vr vc set r [expr {($pr + $vr*$turn) % $rows}] set c [expr {($pc + $vc*$turn) % $cols}] lset grid $r $c 1 } # Look for any grid that has a horizontal line of 20+ robots. set match 0 foreach row $grid { set string "" foreach c $row { append string $c } if {[string match *11111111111111111111* $string]} { set match 1 break } } if {$match} { set fd [open $turn.pbm w] puts $fd P1 puts $fd "$cols $rows" foreach row $grid { puts $fd $row } close $fd puts $turn } incr turn } } input search