Public
Edited
Mar 3, 2023
2 forks
1 star
Insert cell
Insert cell
Insert cell
all = d3
.map(
run(
d3.range(0, 10).map(() => [0, 0]),
data
),
(d) => d
)
.flatMap((knots, t) => knots.map(([x, y], i) => ({ t, x, y, i })))
Insert cell
part2 = new Set(d3.map(run(d3.range(0, 10).map(() => [0, 0]), data), d => String(d[9]))).size
Insert cell
part1 = new Set(d3.map(run([[0, 0], [0, 0]], data), d => String(d[1]))).size
Insert cell
function* run(initial, src) {
let state = initial;
yield state;
for (const { dir, n } of steps(src))
for (let i = 0; i < n; i++) yield (state = step(state, dir));
}
Insert cell
step = (state, dir) => {
const next = state.map((p) => p.slice());
const [head] = next;

// move head
head[0] += dirs[dir][0];
head[1] += dirs[dir][1];

// fix knots
for (let i = 1; i < next.length; i++) {
const t = next[i];
const [hx, hy] = next[i - 1];
const [dx, dy] = [hx - t[0], hy - t[1]];
if (Math.abs(dx) === 2) {
t[0] += Math.sign(dx);
if (Math.abs(dy) >= 1) t[1] += Math.sign(dy);
} else if (Math.abs(dy) === 2) {
t[1] += Math.sign(dy);
if (Math.abs(dx) >= 1) t[0] += Math.sign(dx);
}
}

return next;
}
Insert cell
dirs = ({ R: [1, 0], L: [-1, 0], U: [0, 1], D: [0, -1] })
Insert cell
steps = (src) =>
src
.trim()
.split("\n")
.map((l) => {
const [dir, n] = l.split(" ");
return { dir, n: +n };
})
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