DEV Community

Discussion on: AoC Day 18: Settlers of The North Pole

Collapse
 
choroba profile image
E. Choroba • Edited

Very similar to Conway's Life, but the result is kind of more life-like.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @grid;
while (<>) {
    chomp;
    push @grid, [ split // ];
}

for (1.. 10) {
    my @next;
    for my $y (0 .. $#grid) {
        for my $x (0 .. $#{ $grid[$y] }) {
            my %adjacent;
            my @coords = grep   $_->[0] >= 0 && $_->[0] <= $#{ $grid[$y] }
                             && $_->[1] >= 0 && $_->[1] <= $#grid,
                         [$x - 1, $y - 1], [$x, $y - 1], [$x + 1, $y - 1],
                         [$x - 1, $y    ],               [$x + 1, $y    ],
                         [$x - 1, $y + 1], [$x, $y + 1], [$x + 1, $y + 1];
            ++$adjacent{ $grid[ $_->[0] ][ $_->[1] ] } for @coords;
            $next[$x][$y] = {
                '.' => sub { ($adjacent{'|'} // 0) >= 3 ? '|' : '.' },
                '|' => sub { ($adjacent{'#'} // 0) >= 3 ? '#' : '|' },
                '#' => sub { ($adjacent{'#'} && $adjacent{'|'}) ? '#' : '.' },
            }->{ $grid[$x][$y] }->();
        }
    }
    @grid = @next;
}

my %count;
++$count{$_} for map @$_, @grid;
say +($count{'|'} // 0) * ($count{'#'} // 0);

Animation