Public
Edited
Dec 6, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
testInput = ` [D]
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2`
Insert cell
input = FileAttachment("input.txt").text()
Insert cell
rawInfo = input.split("\n\n");
Insert cell
rawStacks = rawInfo[0];
Insert cell
function getStacks(raw) {
const splitStacks = raw.split("\n");
const {length} = splitStacks.at(-1);
const columns = [];
for (let i = 1; i <= length; i += 4) {
columns.push(splitStacks.map(row => row.charAt(i)).filter(c => c.length && c !== " ").reverse().slice(1));
}
return columns;
}
Insert cell
stacks = getStacks(rawStacks);
Insert cell
rawProcedures = rawInfo[1];
Insert cell
function getProcedures(raw) {
return raw
.trim()
.split("\n")
.map(line => line
.split(" ")
.map(word => Number(word))
.filter(num => !Number.isNaN(num))
.map((val, i) => i > 0 ? val -1 : val)
);
}
Insert cell
procedures = getProcedures(rawProcedures);
Insert cell
function moveStacksSingle(startStacks, procedures) {
// Create copy of stacks
const stacks = [...startStacks.map(col => [...col])];
procedures.forEach(([amount, indexFrom, indexTo]) => {
const transfer = stacks[indexFrom].splice(-amount, amount);
stacks[indexTo].push(...transfer.reverse());
});

return stacks;
}
Insert cell
stackTopsSingle = moveStacksSingle(stacks, procedures).map(col => col.at(-1)).join("");
Insert cell
Insert cell
function moveStacksMultiple(startStacks, procedures) {
// Create copy of stacks
const stacks = [...startStacks.map(col => [...col])];
procedures.forEach(([amount, indexFrom, indexTo]) => {
const transfer = stacks[indexFrom].splice(-amount, amount);
stacks[indexTo].push(...transfer);
});

return stacks;
}
Insert cell
stackTopsMultiple = moveStacksMultiple(stacks, procedures).map(col => col.at(-1)).join("");
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