]> www.fi.muni.cz Git - aoc.git/blob - 2018/24.pl
Day 25: examining the input
[aoc.git] / 2018 / 24.pl
1 #!/usr/bin/perl -w
2
3 use v5.30;
4 use strict;
5
6 chomp (my $state = <>);
7 $state =~ s/.*: //;
8
9 scalar <>;
10
11 my %rules;
12 while (<>) {
13         chomp;
14         my ($src, $dst) = split / => /;
15         $rules{$src} = $dst;
16 }
17
18 my $off = 0;
19 my %seen;
20 my $gen = 0;
21 while (1) {
22         $gen++;
23         if ($state !~ /^\.\.\.\./) {
24                 $state = '....' . $state;
25                 $off -= 4;
26         }
27         $state = $state . '....' if $state !~ /\.\.\.\.$/;
28         while ($state =~ /^\.\.\.\.\./) {
29                 $state =~ s/^.//;
30                 $off++;
31         }
32         while ($state =~ /\.\.\.\.\.$/) {
33                 $state =~ s/.$//;
34         }
35
36         my $nstate = $state;
37         $nstate =~ y/#/./;
38
39         for my $p (2 .. length($state)-3) {
40                 my $src = substr($state, $p-2, 5);
41                 # die "no rule for $src" if !exists $rules{$src};
42                 substr($nstate, $p, 1) = $rules{$src} if defined $rules{$src};
43         }
44         $state = $nstate;
45         last if ($seen{$state});
46         $seen{$state} = [ $gen, $off ];
47         say $state;
48 }
49
50 say "state $gen off $off";
51 say $state;
52 say "is equal to ", $seen{$state}[0], ' ', $seen{$state}[1];
53
54 $off += (50000000000 - $gen) * ($off - $seen{$state}[1]);
55 my $sum;
56 while ($state =~ /#/g) {
57         $sum += pos($state) + $off - 1;
58 }
59 say $sum;