From 1eaf6eece16f10bdc7362541277f5ab08b27d780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment?= Date: Wed, 9 Dec 2020 13:06:05 +0100 Subject: [PATCH] :sparkles: Finit le jour 8 --- day_8/part_1.php | 44 ++++++++++++++++++++++++++++++ day_8/part_2.php | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 day_8/part_1.php create mode 100644 day_8/part_2.php diff --git a/day_8/part_1.php b/day_8/part_1.php new file mode 100644 index 0000000..3604954 --- /dev/null +++ b/day_8/part_1.php @@ -0,0 +1,44 @@ + $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; + } +}