68 lines
1.4 KiB
JavaScript
68 lines
1.4 KiB
JavaScript
import * as R from "remeda";
|
|
|
|
import { readFile } from "../03/part1.js";
|
|
|
|
export const sample = readFile("2022", "05", "sample");
|
|
export const puzzleInput = readFile("2022", "05", "input");
|
|
|
|
function parseHeaps(text) {
|
|
const lines = text.split("\n").filter( R.identity );
|
|
lines.reverse();
|
|
|
|
let [ header, ...crates ] = lines;
|
|
|
|
const stacks = [];
|
|
|
|
while(header.trimEnd()) {
|
|
|
|
header = header.replace( /^(\s+)\d/, (...args) => {
|
|
crates = crates.map( c => c.slice(args[1].length) );
|
|
|
|
const stack = [];
|
|
|
|
crates = crates.map( l => l.replace(/./, (c) => {
|
|
if( c !== ' ' ) stack.push(c);
|
|
return '';
|
|
}));
|
|
|
|
|
|
stacks.push(stack);
|
|
|
|
return '';
|
|
});
|
|
}
|
|
|
|
return stacks;
|
|
}
|
|
|
|
function parseCommands(text) {
|
|
return text.split("\n").filter(R.identity).map(
|
|
line => line.match(/\d+/g).map( x => parseInt(x) )
|
|
)
|
|
}
|
|
|
|
function moveStacks([stacks,commands]) {
|
|
for( let [move, from, to] of commands ) {
|
|
console.log({move,from,to});
|
|
|
|
while(move-- > 0) {
|
|
stacks[to-1].push( stacks[from-1].pop() );
|
|
}
|
|
|
|
}
|
|
|
|
return stacks;
|
|
}
|
|
|
|
const spy = x => { console.log(x); return x; }
|
|
|
|
export const solutionPart1 = R.createPipe(
|
|
text => text.split("\n\n"),
|
|
([heaps,commands]) => [ parseHeaps(heaps), parseCommands(commands) ],
|
|
moveStacks,
|
|
spy,
|
|
R.map( x => x.pop() ),
|
|
x => x.join('')
|
|
)
|
|
|