Public
Edited
Dec 6, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parseStack(input) {
const stacks = [];
const moves = [];
const [part1, part2] = input.split("\n\n");

for (const line of part1.split("\n").slice(0, -1)) {
for (let i = 1, n = line.length, j = 1; i < n; i += 4, ++j) {
switch (line[i]) {
case " ": continue;
default:
(stacks[j] ??= []).push(line[i]);
break;
}
}
}

for (const line of part2.trim().split("\n")) {
const {groups: {n, src, dst}} = /^move (?<n>\d+) from (?<src>\d+) to (?<dst>\d+)$/.exec(line);
moves.push({n, src, dst});
}
return {stacks, moves};
}
Insert cell
testState = parseStack(test)
Insert cell
Insert cell
{
let i = 0;
for (const stacks of processMoves(testState)) {
yield stacks;
if (++i > testStep) break;
}
}
Insert cell
function* processMoves({stacks, moves}) {
stacks = stacks.map((stack) => stack.slice());
yield stacks;
for (let {n, src, dst} of moves) {
src = stacks[src];
dst = stacks[dst];
for (let i = 0; i < n; ++i) {
dst.unshift(src.shift());
}
yield stacks;
}
}
Insert cell
input = FileAttachment("input.txt").text()
Insert cell
state = parseStack(input)
Insert cell
stacks = processMoves(state)
Insert cell
getTopCrates(stacks)
Insert cell
function getTopCrates(stacks) {
return stacks.map((stack) => stack[0]).slice(1).join("");
}
Insert cell
Insert cell
function* processMoves9001({stacks, moves}) {
stacks = stacks.map((stack) => stack.slice());
yield stacks;
for (let {n, src, dst} of moves) {
src = stacks[src];
dst = stacks[dst];
dst.unshift(...src.splice(0, n));
yield stacks;
}
}
Insert cell
Insert cell
{
let i = 0;
for (const stacks of processMoves9001(testState)) {
yield stacks;
if (++i > testStep2) break;
}
}
Insert cell
stacks2 = processMoves9001(state)
Insert cell
getTopCrates(stacks2)
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