Advertisement
mscha

AoC 2016 day 12 (version 2)

Dec 12th, 2016
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.95 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 %.register = :a(0), :b(0), :c(0), :d(0);
  10.  
  11.     method value-of(Str() $val)
  12.     {
  13.         if ($val eq any <a b c d>) {
  14.             return "\$$val";
  15.         }
  16.         else {
  17.             return $val;
  18.         }
  19.     }
  20.  
  21.     method run()
  22.     {
  23.         my token reg { <[abcd]> };
  24.         my token val { '-'? \d+ | <[abcd]> }
  25.  
  26.         my $perl5file = '/tmp/aoc_2016_12.pl';
  27.         my $fh = open $perl5file, :w;
  28.  
  29.         $fh.say: q:to/END/;
  30.                 #!/usr/bin/env perl
  31.                 use 5.010;
  32.                 END
  33.         $fh.say: "my \$$_ = %!register{$_};" for <a b c d>;
  34.         $fh.say: "";
  35.  
  36.         while @!instructions[$!pos] {
  37.             $fh.say: "LABEL{$!pos+1}:";
  38.             given @!instructions[$!pos++] {
  39.                 when /^ cpy \s+ <val> \s+ <reg> $/ {
  40.                     $fh.say: "    \$$/<reg> = { self.value-of($/<val>) };";
  41.                 }
  42.                 when /^ inc \s+ <reg> $/ {
  43.                     $fh.say: "    ++\$$/<reg>;";
  44.                 }
  45.                 when /^ dec \s+ <reg> $/ {
  46.                     $fh.say: "    --\$$/<reg>;";
  47.                 }
  48.                 when /^ jnz \s+ <nonzero=val> \s+ <offset=val> $/ {
  49.                     $fh.say: "    goto LABEL{ $!pos + self.value-of($/<offset>) } if { self.value-of($/<nonzero>) };"
  50.                 }
  51.                 default {
  52.                     die "Invalid instruction: $_";
  53.                 }
  54.             }
  55.         }
  56.  
  57.         $fh.say: "";
  58.         $fh.say: "say \"$_ = \$$_\";" for <a b c d>;
  59.  
  60.         $fh.close;
  61.  
  62.         $perl5file.IO.chmod(0o755);
  63.         run $perl5file;
  64.     }
  65. }
  66.  
  67. #| AoC 2016 day 12 - version 2
  68. sub MAIN(IO() $inputfile where *.f, Int :$a=0, Int :$b=0, Int :$c=0, Int :$d=0)
  69. {
  70.     my $computer = Computer.new(:instructions($inputfile.lines));
  71.     $computer.register<a b c d> = $a, $b, $c, $d;
  72.     $computer.run;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement