Public
Edited
Dec 6, 2022
Insert cell
Insert cell
Insert cell
finalStacks.map((s) => s.peek()).join("")
Insert cell
finalStacks = {
// run steps
for (const step of steps) {
const split = step.split(" ");
for (let i = 0; i < +split[1]; i++) {
const from = +split[3] - 1;
const to = +split[5] - 1;
const popped = stacks[from].pop();
stacks[to].push(popped);
}
}
return stacks;
}
Insert cell
stacks = {
// parse stacks
const stacks = [];
for (let i = 0; i < 9; i++) stacks.push(new Stack());
for (const line of Array.from(crates).reverse().slice(1)) {
const split = line.split("");
for (let i = 0; i < line.length; i += 4) {
const index = Math.floor(i / 4);
if (line[i] === "[") stacks[index].push(line[i + 1]);
}
}
return stacks;
}
Insert cell
{
for (const step of steps) {
return step.split(" ");
}
}
Insert cell
// 0 1 2 --> 1
// 4 5 6 --> 2
// 8 9 10 --> 3
// 12 13 14 --> 4
Insert cell
Insert cell
stacks2 = {
// parse stacks
const stacks = [];
for (let i = 0; i < 9; i++) stacks.push(new Stack());
for (const line of Array.from(crates).reverse().slice(1)) {
const split = line.split("");
for (let i = 0; i < line.length; i += 4) {
const index = Math.floor(i / 4);
if (line[i] === "[") stacks[index].push(line[i + 1]);
}
}
return stacks;
}
Insert cell
finalStacks2 = {
// run steps
for (const step of steps) {
const split = step.split(" ");
const from = +split[3] - 1;
const to = +split[5] - 1;
const toPush = [];
for (let i = 0; i < +split[1]; i++) {
const popped = stacks2[from].pop();
toPush.push(popped);
}
for (const p of toPush.reverse()) {
stacks2[to].push(p);
}
}
return stacks2;
}
Insert cell
finalStacks2.map((s) => s.peek()).join("")
Insert cell
Insert cell
crates = rawInput.split("\n\n")[0].split("\n")
Insert cell
steps = rawInput.split("\n\n")[1].split("\n")
Insert cell
rawInput = FileAttachment("crates.txt").text()
Insert cell
[1, 2, 3].slice(-1)
Insert cell
class Stack {
constructor() {
this.arr = [];
}
// modified push that preserves order of array inputs
push(elem) {
if (Array.isArray(elem)) this.arr.concat(elem);
else this.arr.push(elem);
}
// modified pop that optionally pops multiple elements and preserves their order
pop(n = 1) {
const popped = this.arr.slice(-n);
this.arr = this.arr.slice(0, this.arr.length - n);
return n === 1 ? popped[0] : popped;
}
peek() {
return this.arr[this.arr.length - 1];
}
}
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