Finit le jour 8

This commit is contained in:
Clément 2020-12-09 13:06:05 +01:00
parent 46b650a808
commit 1eaf6eece1
2 changed files with 115 additions and 0 deletions

44
day_8/part_1.php Normal file
View File

@ -0,0 +1,44 @@
<?php
$instructions = explode("\n", file_get_contents('input.txt'));
$acc = 0;
$used_indexes = [];
$current_index = 0;
while (true) {
if (in_array($current_index, $used_indexes, true)) {
echo $acc;
exit;
}
$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;
}
}

71
day_8/part_2.php Normal file
View File

@ -0,0 +1,71 @@
<?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;
}
}