advent_of_code_2021/day_5/part_1.php
2021-12-06 15:31:47 +01:00

46 lines
1.2 KiB
PHP

<?php
$coordinates = array_map(static function ($line) {
preg_match('/^(\d+),(\d+) -> (\d+),(\d+)$/', $line, $matches);
array_shift($matches);
return $matches;
}, explode("\n", file_get_contents('./input.txt')));
$grid = array_fill(0, 1000, array_fill(0, 1000, 0));
foreach ($coordinates as $coordinate) {
if (is_horizontal($coordinate)) {
$axis = $coordinate[0];
$min = min($coordinate[1], $coordinate[3]);
$max = max($coordinate[1], $coordinate[3]);
for ($i = $min; $i <= $max; $i++) {
$grid[$axis][$i]++;
}
} elseif (is_vertical($coordinate)) {
$axis = $coordinate[1];
$min = min($coordinate[0], $coordinate[2]);
$max = max($coordinate[0], $coordinate[2]);
for ($i = $min; $i <= $max; $i++) {
$grid[$i][$axis]++;
}
}
}
$count = 0;
foreach ($grid as $row) {
$count += count(array_filter($row, static function($cell) {
return $cell >= 2;
}));
}
echo $count;
function is_horizontal($coordinate)
{
return $coordinate[0] === $coordinate[2];
}
function is_vertical($coordinate)
{
return $coordinate[1] === $coordinate[3];
}