Files
advent_of_code_2025/day_4/part_1.php
2025-12-11 14:51:22 +01:00

54 lines
1.7 KiB
PHP

<?php
$grid = array_map(fn($line) => str_split($line), array_filter(explode("\n", file_get_contents(__DIR__.'/input.txt')), static fn($line) =>!empty($line)));
$count = 0;
do {
$local_count = 0;
$removed_papers = [];
foreach ($grid as $i => $line) {
foreach ($line as $j => $cell) {
switch ($cell) {
case '@':
if (count_adjacents($i, $j) < 4) {
$local_count++;
$removed_papers[] = [$i, $j];
}
break;
case '.':
default:
break;
}
}
}
foreach ($removed_papers as $removed_paper) {
$grid[$removed_paper[0]][$removed_paper[1]] = '.';
}
$count += $local_count;
} while ($local_count !== 0);
echo $count;
function count_adjacents(int $i, int $j): int
{
global $grid;
$count = 0;
if (array_key_exists($i - 1, $grid)) {
if (array_key_exists($j - 1, $grid[$i - 1]) && $grid[$i - 1][$j - 1] === '@') $count++;
if ($grid[$i - 1][$j] === '@') $count++;
if (array_key_exists($j + 1, $grid[$i - 1]) && $grid[$i - 1][$j + 1] === '@') $count++;
}
if (array_key_exists($j - 1, $grid[$i]) && $grid[$i][$j - 1] === '@') $count++;
if (array_key_exists($j + 1, $grid[$i]) && $grid[$i][$j + 1] === '@') $count++;
if (array_key_exists($i + 1, $grid)) {
if (array_key_exists($j - 1, $grid[$i + 1]) && $grid[$i + 1][$j - 1] === '@') $count++;
if ($grid[$i + 1][$j] === '@') $count++;
if (array_key_exists($j + 1, $grid[$i + 1]) && $grid[$i + 1][$j + 1] === '@') $count++;
}
return $count;
}