sol2.pl (1084B) [raw]
1 #!/usr/bin/env perl 2 use strict; 3 use warnings; 4 5 open(my $fh, '<', 'input') or die "$!"; 6 my @lines; 7 { 8 local $/; 9 my $content = <$fh>; 10 @lines = split("\n", $content); 11 } 12 13 my $goal = scalar @lines; 14 my $attempts; 15 for (my $i = 0; $i < @lines; $i++) { 16 my ($inst, $val) = split(' ', $lines[$i]); 17 if ($inst eq 'nop') { 18 my @game = @lines; 19 $game[$i] = "jmp $val"; 20 play_out(@game); 21 } elsif ($inst eq 'jmp') { 22 my @game = @lines; 23 $game[$i] = "nop $val"; 24 play_out(@game); 25 } 26 } 27 28 sub play_out { 29 my (@game) = @_; 30 $attempts++; 31 32 my $acc = 0; 33 my $ptr = 0; 34 my %seen; 35 my %C = ( 36 acc => sub { $acc += $_[0]; $ptr++ }, 37 nop => sub { $ptr++ }, 38 jmp => sub { $ptr += $_[0] }, 39 ); 40 41 while ($ptr != $goal) { 42 if (exists $seen{$ptr}) { 43 return 0; 44 } 45 my ($ins, $val) = split(' ', $game[$ptr]); 46 # print "$ptr\t$acc\t$lines[$ptr]\n"; 47 $seen{$ptr} = 1; 48 $C{$ins}->($val); 49 } 50 print "After $attempts attempts: $acc\n"; 51 exit(0); 52 }