#!/usr/bin/perl -w

use v5.16;

my @map = map { chomp; [ split // ] } <>;

my $min;
my %seen;
while (1) {
	say "After ", ++$min, ":";
	my @nm;
	for my $y (0 .. 4) {
	for my $x (0 .. 4) {
		my $sum = 0;
		for my ($dx, $dy) (1, 0, 0, 1, -1, 0, 0, -1) {
			my $nx = $x + $dx;
			my $ny = $y + $dy;
			next if $nx < 0 || $nx > 4 || $ny < 0 || $ny > 4;
			$sum++ if $map[$ny][$nx] eq '#';
		}
		# say "at $x $y neigbors $sum";
		if ($map[$y][$x] eq '#') {
			$nm[$y][$x] = $sum == 1 ? '#' : '.';
		} else {
			$nm[$y][$x] = $sum == 1 || $sum == 2 ? '#' : '.';
		}
		print $nm[$y][$x];
	}
		print "\n";
	}
	@map = @nm;
	my $key = join('', map { join('', @$_) } @map);
	if ($seen{$key}) {
		say "this one was last seen at min $seen{$key}";
		my $b = reverse $key;
		$b =~ tr/.#/01/;
		say oct "0b$b";
		last;
	}
	$seen{$key} = $min;
	print "\n";
}

