adventofcode/2022/14/part2.js

53 lines
1.1 KiB
JavaScript

import * as R from "remeda";
import { genCave, V } from './part1.js';
function pourSand(cave){
cave = R.clone(cave);
let sand = 0;
/** @type Victor */
let current;
const maxDepth = R.pipe(
cave,
R.keys,
R.map( x => parseInt(x) ),
R.maxBy( R.identity ),
) + 1;
while(true) {
if(!current) current = V(500,0);
if( current.y === maxDepth ) {
if( ! cave[current.y] ) cave[current.y] = {};
cave[current.y][current.x] = 'o';
sand++;
current = null;
continue;
}
const next = [ [0,1],[-1,1],[1,1] ].map( args => V(...args) ).map(
v => v.add(current)
).find( v => ! (cave[v.y] && cave[v.y][v.x]) );
if( next ) {
current = next;
}
else {
if( current.y === 0 ) return 1+sand;
if( ! cave[current.y] ) cave[current.y] = {};
cave[current.y][current.x] = 'o';
sand++;
current = null;
}
}
};
export default R.createPipe(
genCave,
pourSand,
)