11th day part 2

This commit is contained in:
kplaczek
2021-12-12 09:22:32 +01:00
parent 1e9b596be1
commit b39c1d5f1c

65
11/part2.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$input = array_map('str_split', $input);
$input = array_map(function ($line) {
array_unshift($line, 9);
array_push($line, 9);
return $line;
}, $input);
array_unshift($input, array_fill(0, count($input[0]), 9));
$input[] = array_fill(0, count($input[0]), 9);
for ($step = 1; $step < 1000; $step++) {
for ($i = 1; $i < count($input[0]) - 1; $i++) {
for ($j = 1; $j < count($input) - 1; $j++) {
++$input[$i][$j];
}
}
[$input, $flashNumber] = checkForFlash($input);
if ($flashNumber == 100) {
echo $step; //418
die();
}
}
function checkForFlash($input)
{
$flashed = [];
do {
for ($i = 1; $i < count($input[0]) - 1; $i++) {
for ($j = 1; $j < count($input) - 1; $j++) {
if ($input[$i][$j] > 9 && !isset($flashed[$i . ',' . $j])) {
$flashed[$i . ',' . $j] = [$i, $j];
$input[$i][$j] = 0;
if (!isset($flashed[$i - 1][$j - 1])) $input[$i - 1][$j - 1]++;
if (!isset($flashed[$i - 1][$j])) $input[$i - 1][$j]++;
if (!isset($flashed[$i - 1][$j + 1])) $input[$i - 1][$j + 1]++;
if (!isset($flashed[$i][$j - 1])) $input[$i][$j - 1]++;
if (!isset($flashed[$i][$j])) $input[$i][$j]++;
if (!isset($flashed[$i][$j + 1])) $input[$i][$j + 1]++;
if (!isset($flashed[$i + 1][$j - 1])) $input[$i + 1][$j - 1]++;
if (!isset($flashed[$i + 1][$j])) $input[$i + 1][$j]++;
if (!isset($flashed[$i + 1][$j + 1])) $input[$i + 1][$j + 1]++;
}
}
}
} while (canFlash($input));
foreach ($flashed as $flash) {
$input[$flash[0]][$flash[1]] = 0;
}
return [$input, count($flashed)];
}
function canFlash($input)
{
for ($i = 1; $i < count($input[0]) - 1; $i++) {
for ($j = 1; $j < count($input) - 1; $j++) {
if ($input[$i][$j] > 9) {
return true;
}
}
}
return false;
}