#!/usr/local/bin/tclsh set state [join [split [read stdin] \n] ""] set seen($state) 1 proc step {state} { # Make a 7x7 grid with empty space. for {set y -1} {$y < 6} {incr y} { for {set x -1} {$x < 6} {incr x} { set grid($x,$y) . } } # Expand the state string into the 5x5 central part of the grid. set i 0 for {set y 0} {$y < 5} {incr y} { for {set x 0} {$x < 5} {incr x} { set grid($x,$y) [string index $state $i] incr i } } # Calculate new state string. set state "" for {set y 0} {$y < 5} {incr y} { for {set x 0} {$x < 5} {incr x} { set neighbors 0 set up [expr {$y-1}]; set down [expr {$y+1}] set left [expr {$x-1}]; set right [expr {$x+1}] if {$grid($x,$up) eq "#"} {incr neighbors} if {$grid($x,$down) eq "#"} {incr neighbors} if {$grid($left,$y) eq "#"} {incr neighbors} if {$grid($right,$y) eq "#"} {incr neighbors} switch -- $grid($x,$y) { # { if {$neighbors == 1} { append state # } else { append state . } } . { if {$neighbors == 1 || $neighbors == 2} { append state # } else { append state . } } } } } return $state } proc diversity {state} { set d 0 set i 1 foreach c [split $state ""] { if {$c eq "#"} {incr d $i} incr i $i } return $d } while 1 { set state [step $state] if {[info exists seen($state)]} break set seen($state) 1 } puts [diversity $state]