#!/usr/bin/perl use strict; use warnings; use Clone qw( clone ); $|++; my $width = 29; my $height = 29; my $world = [ #0 1 2 3 #123456789012345678901234567890 ' ',#1 ' 00 ',#2 ' 0 ',#3 ' 0 ',#4 ' 00 ',#5 ' ',#6 ' ',#7 ' ',#8 ' ',#9 ' ',#10 ' ',#1 ' 000 ',#2 ' ',#3 ' ',#4 ' ',#5 ' ',#6 ' ',#7 ' ',#8 ' ',#9 ' ',#20 ' ',#1 ' ',#2 ' ',#3 ' ',#4 ' ',#5 ' ',#6 ' ',#7 ' ',#8 ' ',#9 ' ',#30 ] ; my $i = 0; print_world($world); while (<>) { chomp; exit if $_ eq 'q'; print "iteration:", $i++, "\n"; $world = iterate($world); print_world($world); } sub print_world { my $world = shift; for my $row (@$world) { print "$row\n"; } }; sub iterate { my $world = shift; my $new_world = clone($world); for my $x (0 .. $width) { for my $y (0 .. $height) { my $n = 0; for my $xc (-1,0,1) { for my $yc ( -1,0,1) { next if $xc == 0 and $yc == 0; my $tx = $x+$xc; next if $tx > $width or $tx < 0; my $ty = $y + $yc; next if $ty > $height or $ty < 0; #warn "$x + $xc = $tx\t$y + $yc = $ty"; my $tmp = substr($world->[$ty], $tx,1); $n++ if $tmp eq '0'; } } substr($new_world->[$y], $x,1) = ' ' if $n < 2 or $n > 3; substr($new_world->[$y], $x,1) = '0' if $n == 3; } } return $new_world; };