$monkeys = [];
// Parse
foreach ($input->lines as $line) {
preg_match("/^([a-z]+)\: (.+)$/", $line, $matches);
if (is_numeric($matches[2]) ) {
$monkeys[$matches[1]] = (int) $matches[2];
} else {
$monkeys[$matches[1]] = explode(" ", $matches[2]);
}
}
function get_solution($monkeys)
{
$previous_missing_monkeys = $missing_monkeys = [];
// Do operations
while (!is_int($monkeys["root"])) {
foreach ($monkeys as $monkey => $value) {
if (is_array($value) && is_int($monkeys[$value[0]]) && is_int($monkeys[$value[2]])) {
switch ($value[1]) {
case "+": $monkeys[$monkey] = $monkeys[$value[0]] + $monkeys[$value[2]]; continue 2;
case "-": $monkeys[$monkey] = $monkeys[$value[0]] - $monkeys[$value[2]]; continue 2;
case "/": $monkeys[$monkey] = $monkeys[$value[0]] / $monkeys[$value[2]]; continue 2;
case "*": $monkeys[$monkey] = $monkeys[$value[0]] * $monkeys[$value[2]]; continue 2;
case "=": return $monkeys[$value[0]] - $monkeys[$value[2]];
}
}
if (is_array($value)) {
$missing_monkeys[] = $monkey;
}
}
// Abort if no new monkey was discoverd and we are stuck in a loop
if ($missing_monkeys == $previous_missing_monkeys) {
return false;
}
$previous_missing_monkeys = $missing_monkeys;
$missing_monkeys = [];
}
return $monkeys["root"];
}
// =============================================================================
// > PART 1
// =============================================================================
$solution_1 = get_solution($monkeys);
// ==================================================
// > PART 2
// > Solution was found by semi-bruteforce.
// > Testing all numbers from 0 to 300 000 revealed that
// > each 10 935 increase starting from 1200, we got 426 560 closer to the solution.
// > Extrapolating this, I was able to find the number of increases needed to reach it.
// ==================================================
$monkeys["root"][1] = "=";
$solution_2 = false;
$found = [];
for ($n = 0; $n <= 0; $n++) { // Was used to get the progression from 0 to 300000
$test = $monkeys;
$test["humn"] = $n;
if (($diff = get_solution($test)) === 0) {
$solution_2 = $n;
break;
} elseif ($diff) {
$found[$n] = $diff;
}
}
$solution_2 = 1200 + (282869317 * 10935);