#!/usr/bin/env tclsh set y 0 while {[gets stdin line] >= 0} { if {$line eq ""} continue set x 0 foreach c [split $line {}] { set grid($x,$y) $c append gridstr $c incr x } set width $x incr y } set height $y proc tick {} { global grid gridstr prevgridstr width height set prevgridstr $gridstr set gridstr "" for {set y 0} {$y < $height} {incr y} { for {set x 0} {$x < $width} {incr x} { if {$grid($x,$y) eq "."} { set new($x,$y) $grid($x,$y) append gridstr $new($x,$y) continue } set occ 0 # Northwest: set xx [expr {$x-1}]; set yy [expr {$y-1}] while {$xx >= 0 && $yy >= 0} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx -1; incr yy -1 } # North: set xx $x; set yy [expr {$y-1}] while {$yy >= 0} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr yy -1 } # Northeast: set xx [expr {$x+1}]; set yy [expr {$y-1}] while {$xx < $width && $yy >= 0} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx; incr yy -1 } # West: set xx [expr {$x-1}]; set yy $y while {$xx >= 0} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx -1 } # East: set xx [expr {$x+1}]; set yy $y while {$xx < $width} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx } # Southwest: set xx [expr {$x-1}]; set yy [expr {$y+1}] while {$xx >= 0 && $yy < $height} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx -1; incr yy } # South: set xx $x; set yy [expr {$y+1}] while {$yy < $height} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr yy } # Southeast: set xx [expr {$x+1}]; set yy [expr {$y+1}] while {$xx < $width && $yy < $height} { if {$grid($xx,$yy) eq "#"} {incr occ; break} if {$grid($xx,$yy) eq "L"} break incr xx; incr yy } if {$grid($x,$y) eq "L"} { if {$occ == 0} { set new($x,$y) # } else { set new($x,$y) L } } elseif {$grid($x,$y) eq "#"} { if {$occ >= 5} { set new($x,$y) L } else { set new($x,$y) # } } append gridstr $new($x,$y) } } array unset grid array set grid [array get new] } proc show {g} { global height width set i 0 for {set y 0} {$y < $height} {incr y} { for {set x 0} {$x < $width} {incr x} { puts -nonewline [string index $g $i] incr i } puts "" } puts "" } set prevgridstr "" while 1 { if {$gridstr eq $prevgridstr} break # show $gridstr tick } set n 0 foreach c [split $gridstr {}] { if {$c eq "#"} {incr n} } puts $n