Advent of code 2024/2
Ajax Direct

Answer

Part 1 :
Part 2 :
function is_valid($n, $dampener = false) {
    $dir = $n->last() - $n->first() < 0 ? -1 : 1;
    for ($i = 1; $i < $n->count(); $i++) {
        $diff = ($n[$i] - $n[$i-1]) * $dir;
        // Diff is too big, problem
        if ($diff < 1 || $diff > 3) {
            if (!$dampener) return false;
            // Dampener : retry sequence after removing either left or right number
            return is_valid($n->removeKeys([$i])->values()) || is_valid($n->removeKeys([$i-1])->values());
        }
    }
    return true;
}

// ==================================================
// > PART 1
// ==================================================
$solution_1 = $input->lines->filter(function ($l) {
    return is_valid($l->numbers());
})->count();

// ==================================================
// > PART 2
// ==================================================
$solution_2 = $input->lines->filter(function ($l) {
    return is_valid($l->numbers(), true);
})->count();