Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- # Registers:
- my $acc = 0;
- my $ip = 0;
- my %op_codes = (
- 'acc' => sub { $acc += shift; $ip++ },
- 'jmp' => sub { $ip += shift },
- 'nop' => sub { $ip++ },
- );
- my @code = map { chomp; [split] } <>;
- sub toggle_op {
- my $inst = shift;
- $code[$inst][0] = ($code[$inst][0] eq 'nop') ? 'jmp' : 'nop';
- }
- sub run_vm {
- my $tog = shift;
- my @ran = map { 0 } (0 .. $#code);
- &toggle_op( $tog ) if ($tog != -1);
- $acc = 0;
- $ip = 0;
- while (1) {
- last if ($ip == $#code);
- if (++$ran[$ip] == 2) {
- &toggle_op( $tog ) if ($tog != -1);
- return (0);
- }
- &{$op_codes{ $code[$ip][0] }}( $code[$ip][1] );
- }
- return (1);
- }
- &run_vm( -1 );
- print "Part 1: $acc\n";
- foreach my $i (0 .. $#code) {
- next if ($code[$i][0] eq 'acc');
- if (&run_vm( $i )) {
- print "Part 2: $acc (swapped $i)\n";
- exit (0);
- }
- }
- exit (1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement