advent_of_code_2019/day_2/part_2.php

46 lines
1.1 KiB
PHP
Raw Permalink Normal View History

2019-12-06 14:32:52 +01:00
<?php
$input = explode(',', file_get_contents('input.txt'));
function run_opcode(array $input)
{
$i = 0;
while ($input[$i] !== 99) {
[$operation, $first, $second, $position] = array_slice($input, $i, 4);
switch ($operation) {
case 1:
$input[$position] = $input[$first] + $input[$second];
break;
case 2:
$input[$position] = $input[$first] * $input[$second];
break;
case 99:
return $input[0];
default:
echo 'unknown operation : '.$operation;
exit;
}
$i += 4;
}
return $input[0];
}
$noun = 0;
$verb = 0;
while ($verb !== 99) {
$noun = 0;
while ($noun !== 99) {
$clone_input = $input;
$clone_input[1] = $noun;
$clone_input[2] = $verb;
$magic_number = run_opcode($clone_input);
if ($magic_number === 19690720) {
echo sprintf('noun : %s | verb : %s', $noun, $verb);
}
$noun++;
}
$verb++;
}
echo sprintf("\n".'answer : %u', ((100*$noun)+$verb));