$cmds = (array) $input->lines->map(function ($line) {
[$action, $num] = $line->split(" ");
return [(string) $action, int($num)];
});
function run($cmds) {
$runs = [];
$acc = 0;
for ($i = 0; $i < count($cmds); $i++) {
if (in_array($i, $runs)) return [false, $acc];
$runs[] = $i;
match ($cmds[$i][0]) {
"jmp" => $i += ($cmds[$i][1] - 1),
"acc" => $acc += $cmds[$i][1],
default => null,
};
}
return [true, $acc];
}
// ==================================================
// > PART 1
// ==================================================
[$_, $solution_1] = run($cmds);
// ==================================================
// > PART 2
// ==================================================
foreach ($cmds as $i=>$cmd) {
$replace = ["jmp" => "nop", "nop" => "jmp"][$cmd[0]] ?? false;
if (!$replace) continue;
$try = $cmds;
$try[$i][0] = $replace;
[$finish, $solution_2] = run($try);
if ($finish) break;
}