]> www.fi.muni.cz Git - aoc.git/blob - 2018/36.pl
Year 2018
[aoc.git] / 2018 / 36.pl
1 #!/usr/bin/perl -w
2
3 use v5.36;
4 use strict;
5 use experimental 'multidimensional';
6
7 my @map = map { chomp; [ split // ] } <>;
8
9 my $rows = @map;
10 my $cols = @{ $map[0] };
11 my $periods = 1000000000;
12
13 my $gen = 0;
14 my %seen;
15 while ($gen++ < $periods) {
16         my %total;
17         my @nmap;
18         say "gen $gen";
19         for my $y (0 .. $rows-1) {
20                 my @row;
21                 for my $x (0 .. $cols-1) {
22                         my %count = map { $_ => 0 } ('#', '|', '.');
23                         for my $neigh ([-1,-1], [0, -1], [1, -1],
24                                 [-1, 0], [1, 0],
25                                 [-1, 1], [0, 1], [1, 1]) {
26                                 my $nx = $x + $neigh->[0];
27                                 my $ny = $y + $neigh->[1];
28                                 next if $nx < 0 || $nx >= $cols
29                                         || $ny < 0 || $ny >= $cols;
30                                 $count{$map[$ny][$nx]}++;
31                         }
32                         my $self = $map[$y][$x];
33                         if ($self eq '.' && $count{'|'} >= 3) {
34                                 $self = '|';
35                         } elsif ($self eq '|' && $count{'#'} >= 3) {
36                                 $self = '#';
37                         } elsif ($self eq '#' &&
38                                 ($count{'#'} == 0 || $count{'|'} == 0)) {
39                                 $self = '.';
40                         }
41                         push @row, $self;
42                         $total{$self}++;
43                 }
44                 push @nmap, \@row;
45         }
46         @map = @nmap;
47         my $state = join('', map { join('', @$_, "\n") } @map);
48         
49         say $total{"#"} * $total{'|'};
50         if (defined $seen{$state} && $gen < 500) {
51                 say "at $gen: the same state seen at $seen{$state}";
52                 my $period = $gen - $seen{$state};
53                 say "period $period";
54                 $gen += $period * int(($periods-1-$gen)/$period);
55                 say " => $gen";
56         }
57         $seen{$state} = $gen;
58 }
59