]> www.fi.muni.cz Git - aoc.git/blobdiff - 2018/24.pl
Year 2018
[aoc.git] / 2018 / 24.pl
diff --git a/2018/24.pl b/2018/24.pl
new file mode 100755 (executable)
index 0000000..697a587
--- /dev/null
@@ -0,0 +1,59 @@
+#!/usr/bin/perl -w
+
+use v5.30;
+use strict;
+
+chomp (my $state = <>);
+$state =~ s/.*: //;
+
+scalar <>;
+
+my %rules;
+while (<>) {
+       chomp;
+       my ($src, $dst) = split / => /;
+       $rules{$src} = $dst;
+}
+
+my $off = 0;
+my %seen;
+my $gen = 0;
+while (1) {
+       $gen++;
+       if ($state !~ /^\.\.\.\./) {
+               $state = '....' . $state;
+               $off -= 4;
+       }
+       $state = $state . '....' if $state !~ /\.\.\.\.$/;
+       while ($state =~ /^\.\.\.\.\./) {
+               $state =~ s/^.//;
+               $off++;
+       }
+       while ($state =~ /\.\.\.\.\.$/) {
+               $state =~ s/.$//;
+       }
+
+       my $nstate = $state;
+       $nstate =~ y/#/./;
+
+       for my $p (2 .. length($state)-3) {
+               my $src = substr($state, $p-2, 5);
+               # die "no rule for $src" if !exists $rules{$src};
+               substr($nstate, $p, 1) = $rules{$src} if defined $rules{$src};
+       }
+       $state = $nstate;
+       last if ($seen{$state});
+       $seen{$state} = [ $gen, $off ];
+       say $state;
+}
+
+say "state $gen off $off";
+say $state;
+say "is equal to ", $seen{$state}[0], ' ', $seen{$state}[1];
+
+$off += (50000000000 - $gen) * ($off - $seen{$state}[1]);
+my $sum;
+while ($state =~ /#/g) {
+       $sum += pos($state) + $off - 1;
+}
+say $sum;