72 lines
2.0 KiB
PHP
72 lines
2.0 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]++;
|
|
}
|
|
} else {
|
|
$x_a = $coordinate[0];
|
|
$y_a = $coordinate[1];
|
|
$x_b = $coordinate[2];
|
|
$y_b = $coordinate[3];
|
|
if ($x_a < $x_b) {
|
|
if ($y_a < $y_b) {
|
|
for ($i = 0; $i <= $x_b - $x_a; $i++) {
|
|
$grid[$x_a + $i][$y_a + $i]++;
|
|
}
|
|
} else {
|
|
for ($i = 0; $i <= $x_b - $x_a; $i++) {
|
|
$grid[$x_a + $i][$y_a - $i]++;
|
|
}
|
|
}
|
|
} else {
|
|
if ($y_a < $y_b) {
|
|
for ($i = 0; $i <= $x_a - $x_b; $i++) {
|
|
$grid[$x_a - $i][$y_a + $i]++;
|
|
}
|
|
} else {
|
|
for ($i = 0; $i <= $x_a - $x_b; $i++) {
|
|
$grid[$x_a - $i][$y_a - $i]++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
$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];
|
|
} |