✨ Finit les 3e et 4e jours
This commit is contained in:
54
day_4/part_1.php
Normal file
54
day_4/part_1.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?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;
|
||||
}
|
||||
Reference in New Issue
Block a user