advent_of_code_2020/day_8/part_2.php
2020-12-09 13:06:05 +01:00

72 lines
1.9 KiB
PHP

<?php
$instructions = explode("\n", file_get_contents('input.txt'));
$acc = 0;
$used_indexes = [];
$current_index = 0;
$to_change = [];
// find all nop and jmp indexes
foreach ($instructions as $index => $instruction) {
if (in_array(substr($instruction, 0, 3), ['nop', 'jmp'])) {
$to_change[] = $index;
}
}
// copy instructions
$original_instructions = $instructions;
while (true) {
if (!array_key_exists($current_index, $instructions)) {
echo $acc;
exit;
}
if (in_array($current_index, $used_indexes, true)) {
// fail, reset and change next nop or jmp
$acc = 0;
$used_indexes = [];
$current_index = 0;
$instructions = $original_instructions;
$changed_instruction_index = array_shift($to_change);
$instruction_to_change = $instructions[$changed_instruction_index];
[$command, $math] = explode(' ', $instruction_to_change);
if ($command === 'nop') {
$instructions[$changed_instruction_index] = sprintf('jmp %s', $math);
} else {
$instructions[$changed_instruction_index] = sprintf('nop %s', $math);
}
continue;
}
$used_indexes[] = $current_index;
$current_op = $instructions[$current_index];
[$command, $value] = explode(' ', $current_op);
if ($command === 'nop') {
$current_index++;
continue;
}
$math_op = $value[0];
$math_value = substr($value, 1);
if ($command === 'acc') {
if ($math_op === '+') {
$acc += (int)$math_value;
} else {
$acc -= (int)$math_value;
}
$current_index++;
continue;
}
if ($command === 'jmp') {
if ($math_op === '+') {
$current_index += (int)$math_value;
} else {
$current_index -= (int)$math_value;
}
continue;
}
}