function solve($input, $ops) {
return $input->lines->map(function ($l) use ($ops) {
$n = (array) $l->numbers();
$goal = array_shift($n);
$queue = [$n];
while ($n = array_pop($queue)) {
$digit = array_shift($n);
foreach ($ops as $op) {
$try = $n;
$try[0] = $op($digit, $try[0]);
if (count($try) == 1) {
if ($try[0] == $goal) return $goal;
} else {
// Stop if lowest possible is over
if (array_sum(array_diff($try, [1])) > $goal) continue;
// Stop if highest possible is bellow
if (implode("", $try) < $goal) continue;
$queue[] = $try;
}
}
}
return 0;
})->sum();
}
// ==================================================
// > PART 1
// ==================================================
$op = [
"+" => fn ($a, $b) => $a + $b,
"*" => fn ($a, $b) => $a * $b,
];
$solution_1 = solve($input, $op);
// ==================================================
// > PART 2
// ==================================================
$op["||"] = fn ($a, $b) => $a . $b;
$solution_2 = solve($input, $op);