From 23a90beb38550820733e952016ad6d95bbe06816 Mon Sep 17 00:00:00 2001 From: Clement Desmidt Date: Fri, 10 Dec 2021 16:10:34 +0100 Subject: [PATCH] :sparkles: Finit le jour 9 --- day_9/part_2.php | 99 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 day_9/part_2.php diff --git a/day_9/part_2.php b/day_9/part_2.php new file mode 100644 index 0000000..02412bb --- /dev/null +++ b/day_9/part_2.php @@ -0,0 +1,99 @@ + $row) { + foreach ($row as $j => $cell) { + $count = 0; + if (!array_key_exists($i - 1, $grid) || $grid[$i - 1][$j] > $cell) { + $count++; + } + if (!array_key_exists($i + 1, $grid) || $grid[$i + 1][$j] > $cell) { + $count++; + } + if (!array_key_exists($j - 1, $row) || $row[$j - 1] > $cell) { + $count++; + } + if (!array_key_exists($j + 1, $row) || $row[$j + 1] > $cell) { + $count++; + } + + if ($count === 4) { + $low_points[] = [$i, $j]; + } + } +} + +foreach ($low_points as $i => $low_point) { + $points_in_bassin[$i] = build_bassin($grid, [$low_point],0, [$low_point]); +} + +rsort($points_in_bassin); + +echo array_product(array_slice($points_in_bassin, 0, 3)); + +function build_bassin($grid, $neighbours, $count_neighbours = 0, $current_bassin = []) +{ + $step = 0; + $new_neighbours = []; + foreach ($neighbours as $value) { + [$i, $j] = $value; + + if ( + isset($grid[$i][$j - 1]) && + $grid[$i][$j - 1] != 9 && + !in_array([$i, $j - 1], $current_bassin) + ) { + $step++; + $count_neighbours++; + $current_bassin[] = [$i, $j - 1]; + $new_neighbours[] = [$i, $j - 1]; + } + + if ( + isset($grid[$i][$j + 1]) && + $grid[$i][$j + 1] != 9 && + !in_array([$i, $j + 1], $current_bassin) + ) { + $step++; + $count_neighbours++; + $current_bassin[] = [$i, $j + 1]; + $new_neighbours[] = [$i, $j + 1]; + } + + if ( + isset($grid[$i - 1][$j]) && + $grid[$i - 1][$j] != 9 && + !in_array([$i - 1, $j], $current_bassin) + ) { + $step++; + $count_neighbours++; + $current_bassin[] = [$i - 1, $j]; + $new_neighbours[] = [$i - 1, $j]; + } + + if ( + isset($grid[$i + 1][$j]) && + $grid[$i + 1][$j] != 9 && + !in_array([$i + 1, $j], $current_bassin) + ) { + $step++; + $count_neighbours++; + $current_bassin[] = [$i + 1, $j]; + $new_neighbours[] = [$i + 1, $j]; + } + } + + if ($step !== 0) { + return build_bassin($grid, $new_neighbours, $count_neighbours, $current_bassin, 1); + } + + return $count_neighbours + 1; +} + +