9th day both parts

This commit is contained in:
kplaczek
2021-12-10 20:04:11 +01:00
parent cf26c66fc0
commit 3085753552
3 changed files with 109 additions and 0 deletions

31
09/part1.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$input = array_map('str_split', $input);
$sum = 0;
$lowpoints = 0;
for ($i = 0; $i < count($input); $i++) {
for ($j = 0; $j < count($input[0]); $j++) {
$current = $input[$i][$j];
if (isset($input[$i - 1][$j]) && $input[$i - 1][$j] <= $current) {
continue;
}
if (isset($input[$i][$j - 1]) && $input[$i][$j - 1] <= $current) {
continue;
}
if (isset($input[$i][$j + 1]) && $input[$i][$j + 1] <= $current) {
continue;
}
if (isset($input[$i + 1][$j]) && $input[$i + 1][$j] <= $current) {
continue;
}
$sum += $current + 1;
}
}
echo $sum; //500

73
09/part2.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$input = array_map('str_split', $input);
$sum = 0;
$lowpoints = [];
for ($i = 0; $i < count($input); $i++) {
for ($j = 0; $j < count($input[0]); $j++) {
$current = $input[$i][$j];
if (isset($input[$i - 1][$j]) && $input[$i - 1][$j] <= $current) {
continue;
}
if (isset($input[$i][$j - 1]) && $input[$i][$j - 1] <= $current) {
continue;
}
if (isset($input[$i][$j + 1]) && $input[$i][$j + 1] <= $current) {
continue;
}
if (isset($input[$i + 1][$j]) && $input[$i + 1][$j] <= $current) {
continue;
}
$sum += $current + 1;
$lowpoints[] = [$i + 1, $j + 1];
}
}
$basinSizes = [];
$input = array_map(function ($line) {
array_unshift($line, 9);
array_push($line, 9);
return $line;
}, $input);
array_map(fn($line) => array_unshift($line, 9), $input);
array_unshift($input, array_fill(0, count($input[0]), 9));
$input[] = array_fill(0, count($input[0]), 9);
foreach ($lowpoints as $lowpoint) {
$searched = [];
$input[$lowpoint[0]][$lowpoint[1]] = '*';
getBasinSize($input, $lowpoint[0], $lowpoint[1], $searched);
$basinSizes[] = count($searched);
}
function getBasinSize(&$input, $i, $j, &$searched)
{
if (!isset($searched[$i . ',' . $j])) {
$searched[$i . ',' . $j] = 1;
if ($input[$i][$j] != '*') {
$input[$i][$j] = ' ';
}
if ($input[$i - 1][$j] != 9) {
getBasinSize($input, $i - 1, $j, $searched);
}
if ($input[$i][$j - 1] != 9) {
getBasinSize($input, $i, $j - 1, $searched);
}
if ($input[$i][$j + 1] != 9) {
getBasinSize($input, $i, $j + 1, $searched);
}
if ($input[$i + 1][$j] != 9) {
getBasinSize($input, $i + 1, $j, $searched);
}
}
}
rsort($basinSizes);
echo array_product(array_slice($basinSizes, 0, 3)); //970200

View File

@@ -37,5 +37,10 @@
### DAY 8 - Decoding 7-segments displays ### DAY 8 - Decoding 7-segments displays
- [part1](08/part1.php)
- [part2](08/part2.php)
### DAY 9 - Smoke Basin
- [part1](08/part1.php) - [part1](08/part1.php)
- [part2](08/part2.php) - [part2](08/part2.php)