#!/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 "L"} { set occ 0 for {set yy [expr {$y-1}]} {$yy <= $y+1} {incr yy} { for {set xx [expr {$x-1}]} {$xx <= $x+1} {incr xx} { if {$xx < 0 || $xx >= $width} continue if {$yy < 0 || $yy >= $height} continue if {$xx == $x && $yy == $y} continue if {$grid($xx,$yy) eq "#"} {incr occ} } } if {$occ == 0} { set new($x,$y) # } else { set new($x,$y) L } } elseif {$grid($x,$y) eq "#"} { set occ 0 for {set yy [expr {$y-1}]} {$yy <= $y+1} {incr yy} { for {set xx [expr {$x-1}]} {$xx <= $x+1} {incr xx} { if {$xx < 0 || $xx >= $width} continue if {$yy < 0 || $yy >= $height} continue if {$xx == $x && $yy == $y} continue if {$grid($xx,$yy) eq "#"} {incr occ} } } if {$occ >= 4} { set new($x,$y) L } else { set new($x,$y) # } } else { set new($x,$y) $grid($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