Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const [stackText, moveText] = input
.split("\n\n")
.map((block) => block.split("\n"));
const numStacks = Number(
stackText[stackText.length - 1].split(" ").reverse()[1]
);
const stacks = new Array(numStacks).fill().map(() => []);
for (let row = 0; row < stackText.length - 1; row++) {
for (let col = 0; col < numStacks; col++) {
const crate = stackText[row][col * 4 + 1];
if (crate !== " ") {
stacks[col].push(crate);
}
}
}

const moves = moveText
.map((l) => l.split(" "))
.map((tokens) => ({
moveSize: Number(tokens[1]),
from: Number(tokens[3]) - 1, // Zero-indexed array, so reduce stack number by 1
to: Number(tokens[5] - 1) // Zero-indexed array, so reduce stack number by 1
}));

return [stacks, moves];
}
Insert cell
Insert cell
function moveCrates(originalStacks, moves, multiPick = false) {
const stacks = AOC.cloneArray(originalStacks); // We are going to change arrays in place, so clone first.
moves.forEach((move) => {
const toMove = stacks[move.from].splice(0, move.moveSize);
stacks[move.to] = multiPick
? toMove.concat(stacks[move.to])
: toMove.reverse().concat(stacks[move.to]);
});
return stacks;
}
Insert cell
Insert cell
function topCrates(stacks) {
return stacks.map((stack) => stack[0]).join("");
}
Insert cell
function part1(input) {
return topCrates(moveCrates(...parse(puzzleInput)));
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return topCrates(moveCrates(...parse(puzzleInput), true));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more