Advertisement
mscha

AoC 2016 day 12 (version 1)

Dec 12th, 2016
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.91 KB | None | 0 0
  1. #!/usr/bin/env perl6
  2.  
  3. use v6.c;
  4.  
  5. class Computer
  6. {
  7.     has @.instructions;
  8.     has Int $.pos = 0;
  9.     has Int $.counter = 0;
  10.     has %.register = :a(0), :b(0), :c(0), :d(0);
  11.  
  12.     method value-of(Str() $val)
  13.     {
  14.         if ($val eq any <a b c d>) {
  15.             return %.register{$val};
  16.         }
  17.         else {
  18.             return +$val;
  19.         }
  20.     }
  21.  
  22.     method run(Bool :$verbose=False)
  23.     {
  24.         my token reg { <[abcd]> };
  25.         my token val { '-'? \d+ | <[abcd]> }
  26.  
  27.         while @!instructions[$!pos] {
  28.             $!counter++;
  29.             say $!pos, ' [', %.register<a b c d>.join(','), '] ', @!instructions[$!pos]
  30.                     if $verbose;
  31.             given @!instructions[$!pos++] {
  32.                 when /^ cpy \s+ <val> \s+ <reg> $/ {
  33.                     %.register{$/<reg>} = self.value-of($/<val>);
  34.                 }
  35.                 when /^ inc \s+ <reg> $/ {
  36.                     %.register{$/<reg>}++;
  37.                 }
  38.                 when /^ dec \s+ <reg> $/ {
  39.                     %.register{$/<reg>}--;
  40.                 }
  41.                 when /^ jnz \s+ <nonzero=val> \s+ <offset=val> $/ {
  42.                     if self.value-of($/<nonzero>) != 0 {
  43.                         $!pos += self.value-of($/<offset>) - 1;  # Compensate for ++ earlier
  44.                     }
  45.                 }
  46.                 default {
  47.                     die "Invalid instruction: $_";
  48.                 }
  49.             }
  50.         }
  51.     }
  52. }
  53.  
  54. #| AoC 2016 day 12
  55. sub MAIN(IO() $inputfile where *.f, Bool :v(:$verbose)=False,
  56.          Int :$a=0, Int :$b=0, Int :$c=0, Int :$d=0)
  57. {
  58.     my $computer = Computer.new(:instructions($inputfile.lines));
  59.     $computer.register<a b c d> = $a, $b, $c, $d;
  60.     $computer.run(:$verbose);
  61.  
  62.     say "The state of the register: ",
  63.          $computer.register.pairs.sort.map({ "$_.key()=$_.value()"}).join(', ');
  64.     say "$computer.counter() instructions processed.";
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement