From 9870df25fbb4abce884ba5147520ee6a5705ce74 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Fri, 10 Dec 2021 12:16:34 -0500 Subject: [PATCH] 2021-09 --- 2021/09/part1.mjs | 2 +- 2021/09/part2.mjs | 38 +++++++++++++++++++++++++++++++++++++- 2021/09/test.mjs | 4 ++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/2021/09/part1.mjs b/2021/09/part1.mjs index 480dbe5..1ee1073 100644 --- a/2021/09/part1.mjs +++ b/2021/09/part1.mjs @@ -17,7 +17,7 @@ export const genNeighbours = (maxX,maxY) => (x,y) => return true; } ); -const genCoords = grid => ([x,y]) => grid[x][y]; +export const genCoords = grid => ([x,y]) => grid[x][y]; export function solution(grid) { const seen = grid.map( () => [] ); diff --git a/2021/09/part2.mjs b/2021/09/part2.mjs index 4581168..1d49a43 100644 --- a/2021/09/part2.mjs +++ b/2021/09/part2.mjs @@ -4,5 +4,41 @@ import _ from "lodash"; import * as p1 from './part1.mjs'; -export function solution(input) { +function getBasinSize( [x,y], grid, seen ) { + if( seen[x][y] ) return 0; + + seen[x][y] = true; + + if( grid[x][y] == 9 ) return 0; + let size = 1; + + const neighbours = p1.genNeighbours(grid.length,grid[0].length); + const coords = p1.genCoords(grid); + + neighbours(x,y).map( n => getBasinSize(n,grid,seen) ).forEach( + x => size+=x + ); + + return size; +} + +export function solution(grid) { + const seen = grid.map( () => [] ); + let basinSizes = []; + + + for( const x of _.range(grid.length) ) { + for( const y of _.range(grid[x].length) ) { + if( seen[x][y] ) continue; + + if( grid[x][y] == 9 ) { + seen[x][y] = true; + continue; + } + basinSizes.push( getBasinSize([x,y],grid,seen)); + } + } + + basinSizes.sort( (a,b) => a < b ? 1 : -1 ); + return basinSizes.splice(0,3).reduce( (a,b) => a*b ) ; } diff --git a/2021/09/test.mjs b/2021/09/test.mjs index 68da3c2..a0b97b9 100644 --- a/2021/09/test.mjs +++ b/2021/09/test.mjs @@ -18,6 +18,6 @@ tap.test("part1", async (t) => { }); tap.test("part2", async (t) => { - /* t.equal(p2.solution(await sample, 256), 26984457539); */ - /* t.equal(p2.solution(await input, 256), 1622533344325); */ + t.equal(p2.solution(await sample), 1134); + t.equal(p2.solution(await input), 1100682); });