advent_of_code_2021/day_11/part_1.php

54 lines
1.5 KiB
PHP
Raw Permalink Normal View History

2021-12-13 10:41:36 +01:00
<?php
$grid = array_map('str_split', explode("\n", file_get_contents('./input.txt')));
$flashes = 0;
for ($i = 0; $i < 100; $i++) {
foreach ($grid as $k => $row) {
foreach ($row as $j => $cell) {
$grid[$k][$j]++;
}
}
while(has_more_than_nine($grid)) {
foreach ($grid as $k => $row) {
foreach ($row as $j => $cell) {
if ($grid[$k][$j] > 9) {
foreach (range(-1, 1) as $r) {
foreach (range(-1, 1) as $c) {
if ($r === 0 && $c === 0) {
$grid[$k+$r][$j+$c] = 0;
}
if (
array_key_exists($k+$r, $grid) &&
array_key_exists($j+$c, $grid[$k+$r]) &&
$grid[$k+$r][$j+$c] !== 0
) {
$grid[$k+$r][$j+$c]++;
}
}
}
$flashes++;
}
}
}
}
echo sprintf('After step %u%s%s%s', $i + 1, "\n", implode("\n", array_map('implode', $grid)), "\n", "\n");
}
echo $flashes;
function has_more_than_nine($grid)
{
foreach ($grid as $row) {
foreach ($row as $cell) {
if ($cell > 9) {
return true;
}
}
}
return false;
}