#!/usr/bin/env perl
use strict;
use warnings;

open(my $fh, '<', 'input') or die "$!";
my @lines;
{
    local $/;
    my $content = <$fh>;
    @lines = split("\n", $content);
}

my $goal = scalar @lines;
my $attempts;
for (my $i = 0; $i < @lines; $i++) {
    my ($inst, $val) = split(' ', $lines[$i]);
    if ($inst eq 'nop') {
        my @game = @lines;
        $game[$i] = "jmp $val";
        play_out(@game);
    } elsif ($inst eq 'jmp') {
        my @game = @lines;
        $game[$i] = "nop $val";
        play_out(@game);
    }
}

sub play_out {
    my (@game) = @_;
    $attempts++;

    my $acc = 0;
    my $ptr = 0;
    my %seen;
    my %C = (
        acc => sub { $acc += $_[0]; $ptr++ },
        nop => sub { $ptr++ },
        jmp => sub { $ptr += $_[0] },
    );

    while ($ptr != $goal) {
        if (exists $seen{$ptr}) {
            return 0;
        }
        my ($ins, $val) = split(' ', $game[$ptr]);
        # print "$ptr\t$acc\t$lines[$ptr]\n";
        $seen{$ptr} = 1;
        $C{$ins}->($val);
    }
    print "After $attempts attempts: $acc\n";
    exit(0);
}
