Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl6
- use v6.c;
- class Computer
- {
- has @.instructions;
- has Int $.pos = 0;
- has %.register = :a(0), :b(0), :c(0), :d(0);
- method value-of(Str() $val)
- {
- if ($val eq any <a b c d>) {
- return "\$$val";
- }
- else {
- return $val;
- }
- }
- method run()
- {
- my token reg { <[abcd]> };
- my token val { '-'? \d+ | <[abcd]> }
- my $perl5file = '/tmp/aoc_2016_12.pl';
- my $fh = open $perl5file, :w;
- $fh.say: q:to/END/;
- #!/usr/bin/env perl
- use 5.010;
- END
- $fh.say: "my \$$_ = %!register{$_};" for <a b c d>;
- $fh.say: "";
- while @!instructions[$!pos] {
- $fh.say: "LABEL{$!pos+1}:";
- given @!instructions[$!pos++] {
- when /^ cpy \s+ <val> \s+ <reg> $/ {
- $fh.say: " \$$/<reg> = { self.value-of($/<val>) };";
- }
- when /^ inc \s+ <reg> $/ {
- $fh.say: " ++\$$/<reg>;";
- }
- when /^ dec \s+ <reg> $/ {
- $fh.say: " --\$$/<reg>;";
- }
- when /^ jnz \s+ <nonzero=val> \s+ <offset=val> $/ {
- $fh.say: " goto LABEL{ $!pos + self.value-of($/<offset>) } if { self.value-of($/<nonzero>) };"
- }
- default {
- die "Invalid instruction: $_";
- }
- }
- }
- $fh.say: "";
- $fh.say: "say \"$_ = \$$_\";" for <a b c d>;
- $fh.close;
- $perl5file.IO.chmod(0o755);
- run $perl5file;
- }
- }
- #| AoC 2016 day 12 - version 2
- sub MAIN(IO() $inputfile where *.f, Int :$a=0, Int :$b=0, Int :$c=0, Int :$d=0)
- {
- my $computer = Computer.new(:instructions($inputfile.lines));
- $computer.register<a b c d> = $a, $b, $c, $d;
- $computer.run;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement