From: Jan "Yenya" Kasprzak Date: Tue, 8 Dec 2020 06:34:33 +0000 (+0100) Subject: Day 8 X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?p=aoc2020.git;a=commitdiff_plain;h=6e13a909884a11a5f73d465fa5828f2be2f0b82d Day 8 --- diff --git a/15.pl b/15.pl new file mode 100755 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 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"; +}