adventofcode/2021/09/part2.mjs

37 lines
821 B
JavaScript
Raw Normal View History

2021-12-10 15:25:34 +00:00
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
2021-12-10 17:23:45 +00:00
import * as p1 from "./part1.mjs";
2021-12-10 15:25:34 +00:00
2021-12-10 17:23:45 +00:00
function getBasinSize([x, y], grid, seen) {
if (seen[x][y]) return 0;
2021-12-10 17:16:34 +00:00
seen[x][y] = true;
2021-12-10 17:23:45 +00:00
if (grid[x][y] == 9) return 0;
2021-12-10 17:16:34 +00:00
2021-12-10 17:23:45 +00:00
const neighbours = p1.genNeighbours(grid.length, grid[0].length);
2021-12-10 17:16:34 +00:00
2021-12-10 17:23:45 +00:00
return _.sum([
1,
...neighbours(x, y).map((n) => getBasinSize(n, grid, seen)),
]);
2021-12-10 17:16:34 +00:00
}
export function solution(grid) {
2021-12-10 17:23:45 +00:00
const seen = grid.map(() => []);
2021-12-10 17:16:34 +00:00
let basinSizes = [];
2021-12-10 17:23:45 +00:00
for (const x of _.range(grid.length)) {
for (const y of _.range(grid[x].length)) {
basinSizes.push(getBasinSize([x, y], grid, seen));
2021-12-10 17:16:34 +00:00
}
}
2021-12-10 17:23:45 +00:00
return basinSizes
.sort((a, b) => (a > b ? 1 : -1))
.splice(-3)
.reduce(_.multiply);
2021-12-10 15:25:34 +00:00
}