#!/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 ) {
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 ;
$fh.say: "";
while @!instructions[$!pos] {
$fh.say: "LABEL{$!pos+1}:";
given @!instructions[$!pos++] {
when /^ cpy \s+ \s+ $/ {
$fh.say: " \$$/ = { self.value-of($/) };";
}
when /^ inc \s+ $/ {
$fh.say: " ++\$$/;";
}
when /^ dec \s+ $/ {
$fh.say: " --\$$/;";
}
when /^ jnz \s+ \s+ $/ {
$fh.say: " goto LABEL{ $!pos + self.value-of($/) } if { self.value-of($/) };"
}
default {
die "Invalid instruction: $_";
}
}
}
$fh.say: "";
$fh.say: "say \"$_ = \$$_\";" for ;
$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;
$computer.run;
}