]> www.fi.muni.cz Git - aoc.git/commitdiff
Day 8
authorJan "Yenya" Kasprzak <kas@fi.muni.cz>
Tue, 8 Dec 2020 06:34:33 +0000 (07:34 +0100)
committerJan "Yenya" Kasprzak <kas@fi.muni.cz>
Tue, 8 Dec 2020 06:34:33 +0000 (07:34 +0100)
15.pl [new file with mode: 0755]
16.pl [new file with mode: 0755]

diff --git a/15.pl b/15.pl
new file mode 100755 (executable)
index 0000000..f82c817
--- /dev/null
+++ b/15.pl
@@ -0,0 +1,23 @@
+#!/usr/bin/perl -w
+
+use strict;
+
+my @code = map { [ split /\s+/ ] } <>;
+
+my $acc = 0;
+my $pc = 0;
+my %seen;
+
+while (!$seen{$pc}) {
+       $seen{$pc} = 1;
+       my ($ins, $arg) = @{ $code[$pc] };
+       print "pc=$pc, acc=$acc, $ins $arg\n";
+       if ($ins eq 'nop') {
+               $pc++;
+       } elsif ($ins eq 'acc') {
+               $acc += $arg; $pc++;
+       } elsif ($ins eq 'jmp') {
+               $pc += $arg;
+       }
+}
+print "loop at $pc, acc=$acc\n";
diff --git a/16.pl b/16.pl
new file mode 100755 (executable)
index 0000000..3447bfd
--- /dev/null
+++ b/16.pl
@@ -0,0 +1,40 @@
+#!/usr/bin/perl -w
+
+use strict;
+
+my @code = map { [ split /\s+/ ] } <>;
+
+for my $i (0 .. $#code) {
+       if ($code[$i]->[0] eq 'nop') {
+               local $code[$i]->[0] = 'jmp';
+               interp(@code);
+       } elsif ($code[$i]->[0] eq 'jmp') {
+               local $code[$i]->[0] = 'nop';
+               interp(@code);
+       }
+}
+               
+sub interp {
+       my @code = @_;
+       my $acc = 0;
+       my $pc = 0;
+       my %seen;
+
+       while (!$seen{$pc} && $pc != @code) {
+               $seen{$pc} = 1;
+               my ($ins, $arg) = @{ $code[$pc] };
+               print "pc=$pc, acc=$acc, $ins $arg\n";
+               if ($ins eq 'nop') {
+                       $pc++;
+               } elsif ($ins eq 'acc') {
+                       $acc += $arg; $pc++;
+               } elsif ($ins eq 'jmp') {
+                       $pc += $arg;
+               }
+       }
+       if ($pc == @code) {
+               print "terminating with acc=$acc.\n";
+               exit 0;
+       }
+       print "\n";
+}