11th day part 1

This commit is contained in:
kplaczek
2021-12-12 00:11:23 +01:00
parent a49ebe687d
commit 1e9b596be1

85
11/part1.php Normal file
View File

@@ -0,0 +1,85 @@
<?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);
$flashNumberTotal = 0;
for ($step = 0; $step < 100; $step++) {
echo 'STEP ' . $step . "\n\n";
for ($i = 1; $i < count($input[0]) - 1; $i++) {
for ($j = 1; $j < count($input) - 1; $j++) {
++$input[$i][$j];
}
}
[$input, $flashNumber] = checkForFlash($input);
$flashNumberTotal += $flashNumber;
// printInput($input);
// echo implode("\n", array_map(fn($l) => implode('', $l), $input));
echo "\n\n";
}
echo $flashNumberTotal;
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]++;
// printInput($input);
// print_r($flashed);
// readline();
}
}
}
} 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;
}
function printInput($input)
{
for ($i = 1; $i < count($input[0]) - 1; $i++) {
for ($j = 1; $j < count($input) - 1; $j++) {
// echo str_pad($input[$i][$j], '3', ' ', STR_PAD_LEFT);
echo $input[$i][$j];
}
echo "\n";
}
echo "\n";
}
//echo implode("\n", array_map(fn($l) => implode('', $l), $input));