Advertisement
musifter

AoC day 8, Perl brute force

Dec 8th, 2020 (edited)
1,344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.00 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. # Registers:
  7. my $acc = 0;
  8. my $ip  = 0;
  9.  
  10. my %op_codes = (
  11.     'acc' => sub { $acc += shift; $ip++ },
  12.     'jmp' => sub { $ip  += shift },
  13.     'nop' => sub { $ip++ },
  14. );
  15.  
  16. my @code = map { chomp; [split] } <>;
  17.  
  18. sub toggle_op {
  19.     my $inst = shift;
  20.  
  21.     $code[$inst][0] = ($code[$inst][0] eq 'nop') ? 'jmp' : 'nop';
  22. }
  23.  
  24. sub run_vm {
  25.     my $tog = shift;
  26.     my @ran = map { 0 } (0 .. $#code);
  27.  
  28.     &toggle_op( $tog )  if ($tog != -1);
  29.  
  30.     $acc = 0;
  31.     $ip  = 0;
  32.  
  33.     while (1) {
  34.         last  if ($ip == $#code);
  35.         if (++$ran[$ip] == 2) {
  36.             &toggle_op( $tog )  if ($tog != -1);
  37.             return (0);
  38.         }
  39.  
  40.         &{$op_codes{ $code[$ip][0] }}( $code[$ip][1] );
  41.     }
  42.  
  43.     return (1);
  44. }
  45.  
  46. &run_vm( -1 );
  47. print "Part 1: $acc\n";
  48.  
  49. foreach my $i (0 .. $#code) {
  50.     next if ($code[$i][0] eq 'acc');
  51.  
  52.     if (&run_vm( $i )) {
  53.         print "Part 2: $acc (swapped $i)\n";
  54.         exit (0);
  55.     }
  56. }
  57.  
  58. exit (1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement