Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function offset([x1, y1, x2, y2]) {
const [dx, dy] = AOC.vSubtract([x1, y1], [x2, y2]);
if (Math.abs(dx) > 1 || Math.abs(dy) > 1) {
return [dx === 0 ? 0 : Math.sign(dx), dy === 0 ? 0 : Math.sign(dy)];
}
return [0, 0];
}
Insert cell
Insert cell
function move(cmd, rope, tailPositions) {
const magnitude = Number(cmd.slice(2));
const dirVector = {
U: [0, 1],
D: [0, -1],
L: [-1, 0],
R: [1, 0]
};
const step = dirVector[cmd[0]];

for (let i = 0; i < magnitude; i++) {
AOC.overwrite(rope, AOC.vAdd(rope, step));
for (let j = 2; j < rope.length; j += 2) {
const v = offset(rope.slice(j - 2, j + 2));
AOC.overwrite(rope, AOC.vAdd([rope[j], rope[j + 1]], v), j);
}
tailPositions.add(rope[rope.length - 2] + "," + rope[rope.length - 1]);
}
return tailPositions;
}
Insert cell
Insert cell
function simulate(cmds, ropeLen) {
const trail = new Set();
const pos = Array(ropeLen * 2).fill(0);
trail.add(pos[pos.length - 2] + "," + pos[pos.length - 1]);
cmds.split("\n").reduce((t, cmd) => move(cmd, pos, t), trail);
return trail.size;
}
Insert cell
function part1(input) {
return simulate(puzzleInput, 2);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return simulate(puzzleInput, 10);
}
Insert cell
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