function severities($layers, $time, $stop_when_caught = false) {
$severities = [];
foreach ($layers as $layer) {
// Position of scanner in the cycle when starting at $time
$pos = ($layer[0] + $time) % ($layer[1] * 2 - 2);
// Optimization: stop as soon as we get caught
if ($stop_when_caught && !$pos) return true;
// If the scanner is at the top, add the severity to the list
if (!$pos) $severities[] = $layer[0] * $layer[1];
}
return $severities;
}
$layers = (array) $input->numbers()->chunk(2);
// ==================================================
// > PART 1
// ==================================================
$solution_1 = array_sum(severities($layers, 0));
// ==================================================
// > PART 2
// ==================================================
$solution_2 = 0;
while (severities($layers, $solution_2, true)) $solution_2++;