Public
Edited
Dec 10, 2022
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
parse = (s) =>
aoc
.lines((l) => l.split(" "))(s)
.map(([dir, dist]) => ({ dir, dist: +dist }))
Insert cell
function* ropeSteps(input, ropeLength) {
let segments = Array.from({ length: ropeLength }, (d) => ({ x: 0, y: 0 }));

yield _.cloneDeep(segments);
for (const step of input) {
let [dx, dy] = dirToVec(step.dir);
for (let i = 0; i < step.dist; i++) {
segments[0].x += dx;
segments[0].y += dy;

for (let i = 1; i < segments.length; i++) {
let prev = segments[i - 1];
let cur = segments[i];
let sx = prev.x - cur.x;
let sy = prev.y - cur.y;
if (Math.abs(sx) > 1 || Math.abs(sy) > 1) {
cur.x += Math.sign(sx);
cur.y += Math.sign(sy);
}
}

yield _.cloneDeep(segments);
}
}
}
Insert cell
ropeData = Array.from(ropeSteps(parse(inputs.real), 10))
Insert cell
dirToVec = (d) => ({ U: [0, -1], D: [0, 1], R: [-1, 0], L: [1, 0] }[d])
Insert cell
function part1(input) {
let tailSpots = new Set();
for (const [head, tail] of ropeSteps(input, 2)) {
tailSpots.add(`${tail.x},${tail.y}`);
}
return tailSpots.size;
}
Insert cell
function part2(input) {
let tailSpots = new Set();
for (const rope of ropeSteps(input, 10)) {
let tail = rope.at(-1);
tailSpots.add(`${tail.x},${tail.y}`);
}
return tailSpots.size;
}
Insert cell
Insert cell
Insert cell
import { Scrubber } from "@mbostock/scrubber"

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