/**
* The program consists of 14 repeats of the following :
* $x = ($z % 26) + $b;
* $z = (int) ($z / $c);
* if ($w != $x) $z = ($z * 26) + ($w + $a);
* return $z;
* With $w as the nth number and $a, $b, $c as numbers from the input commands.
*
* We have two cases :
* 1. $b is positive and $c is 1 => $z will always increase
* 2. $b is negative and $c is 26 => $z should always decrease, $a is not used
* There are 7 of each, which should balance eachother to reach 0 at the end.
*/
$cmd = $input->split("inp")->filter()->map(function ($block) {
$n = $block->numbers();
$d = $n[2] == 26;
return [$d ? null : $n[9], $d ? $n[3] : null];
})->values();
function solve($cmd, $p2 = false) {
$num = [];
$stack = [];
$digit = $p2 ? 1 : 9;
$calc = $p2 ? "max" : "min";
foreach ($cmd as $i=>[$a, $b]) {
if ($a) {
$stack[] = [$i, $a];
} else {
[$ia, $a] = array_pop($stack);
$diff = $a + $b;
$num[$ia] = $calc($digit, $digit - $diff);
$num[$i] = $calc($digit, $digit + $diff);
}
}
return set($num)->sortKeys()->join("");
}
// ==================================================
// > SOLUTION
// ==================================================
$solution_1 = solve($cmd);
$solution_2 = solve($cmd, true);