// Parsing
$lines = $input->lines->map(function ($line) {
preg_match("/(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)/", $line, $matches);
[$_, $action, $x1, $y1, $x2, $y2] = $matches;
return compact("action", "x1", "y1", "x2", "y2");
});
function get_result_grid($lines, $brightness = false)
{
$grid = [];
foreach ($lines as $l) {
extract($l);
for ($x = $x1; $x <= $x2; $x++) {
for ($y = $y1; $y <= $y2; $y++) {
$coord = "$x;$y";
if ($action == "turn on") {
$grid[$coord] = $brightness ? ($grid[$coord] ?? 0) + 1 : true;
} elseif ($action == "turn off") {
$grid[$coord] = $brightness ? max(($grid[$coord] ?? 0) - 1, 0) : false;
} elseif ($action == "toggle") {
$grid[$coord] = $brightness ? ($grid[$coord] ?? 0) + 2 : (empty($grid[$coord]) ? true : false);
}
}
}
}
return set($grid);
}
// ==================================================
// > SOLUTIONS
// ==================================================
$solution_1 = get_result_grid($lines, false)->filter()->count();
$solution_2 = get_result_grid($lines, true)->sum();