]> www.fi.muni.cz Git - aoc.git/blobdiff - 2019/09.pl
First half of Year 2019
[aoc.git] / 2019 / 09.pl
diff --git a/2019/09.pl b/2019/09.pl
new file mode 100755 (executable)
index 0000000..84f958c
--- /dev/null
@@ -0,0 +1,48 @@
+#!/usr/bin/perl -w
+
+use v5.16;
+
+chomp (my @mem = split /,/, <>);
+
+sub m2val {
+       my ($mref, $addr, $mode) = @_;
+       if ($mode == 0) {
+               return $mref->[ $mref->[$addr] ];
+       } elsif ($mode == 1) {
+               return $mref->[$addr];
+       }
+}
+       
+       
+       
+sub run {
+       my ($mref, $iref) = @_;
+       my @mem = @$mref;
+       my @inputs = @$iref;
+       my $pc = 0;
+       while (1) {
+               my $opcode = $mem[$pc];
+               my $op = int($opcode % 100);
+               my $m1 = int($opcode / 100) % 10;
+               my $m2 = int($opcode / 1000) % 10;
+               if ($op == 1) {
+                       $mem[ $mem[$pc+3] ] = m2val(\@mem, $pc+1, $m1)
+                               + m2val(\@mem, $pc+2, $m2);
+                       $pc += 4;
+               } elsif ($op == 2) {
+                       $mem[ $mem[$pc+3] ] = m2val(\@mem, $pc+1, $m1)
+                               * m2val(\@mem, $pc+2, $m2);
+                       $pc += 4;
+               } elsif ($op == 3) {
+                       $mem[ $mem[$pc+1] ] = shift @inputs;
+                       $pc += 2;
+               } elsif ($op == 4) {
+                       say m2val(\@mem, $pc+1, $m1);
+                       $pc += 2;
+               } elsif ($op == 99) {
+                       last;
+               }
+       }
+}
+
+run(\@mem, [ 1 ]);