Public
Edited
Mar 3, 2023
2 forks
1 star
Insert cell
Insert cell
Insert cell
map = {
const lines = data
.split("\n\n")[0]
.split("\n")
.filter((d) => d);
return new d3.InternMap(
lines.flatMap((l, y) =>
[...l].map((c, x) => [[x, y], c]).filter((d) => d[1] !== " ")
),
String
);
}
Insert cell
extent = [
d3.rollup(
map.keys(),
(r) => d3.extent(r, (d) => d[1]),
(d) => d[0]
),
d3.rollup(
map.keys(),
(r) => d3.extent(r, (d) => d[0]),
(d) => d[1]
)
]
Insert cell
function* directions() {
const string = data.split("\n\n")[1].trim();
for (const [m] of string.matchAll(/\d+|[LR]/g))
yield m === "L" || m === "R" ? m : +m;
}
Insert cell
Insert cell
function* path() {
let state = [[extent[1].get(0)[0], 0], [1, 0]];
for (const i of directions()) {
yield state;
state = next(state, i);
}
}
Insert cell
Insert cell
part1 = {
const [[x, y], d] = d3.reduce(path(), (s, d) => d);
const c = x + 1,
r = y + 1,
f = { "1,0": 0, "0,1": 1, "-1,0": 2, "0,-1": 3 }[String(d)];
return 1000 * r + 4 * c + f;
}
Insert cell
Insert cell
Insert cell
Insert cell
d3.zip(boundary, edge)
Insert cell
seams = new d3.InternMap(
[
...seam([4, 3], [7, 3], [8, 0], [8, 3]),
...seam([7, 3], [7, 0], [7, 4], [4, 4])
],
String
)
Insert cell
seam = (n1, n2, m1, m2) => d3.zip([...range(n1, n2)], [...range(m1, m2)])
Insert cell
seam([4, 3], [7, 3], [8, 0], [8, 3])
Insert cell
Insert cell
function* range([x1, y1], [x2, y2]) {
const dx = Math.sign(x2 - x1),
dy = Math.sign(y2 - y1);
const dir = [dy, -dx];
yield [[x1, y1], dir];
while (x1 !== x2 || y1 !== y2) {
x1 += dx;
y1 += dy;
yield [[x1, y1], dir];
}
}
Insert cell
next2 = ([[x, y], [dx, dy]], instruction) => {
switch (instruction) {
case "R":
return [
[x, y],
[-dy, dx]
];
case "L":
return [
[x, y],
[dy, -dx]
];
default: // move
for (let i = 0; i < instruction; i++) {
let n = [x + dx, y + dy];
if (!map.has(n)) { // wrap
if (dx) n[0] = extent[1].get(n[1])[dx > 0 ? 0 : 1];
else n[1] = extent[0].get(n[0])[dy > 0 ? 0 : 1];
}
if (map.get(n) === "#") break;
[x, y] = n;
}
return [
[x, y],
[dx, dy]
];
}
}
Insert cell
data = which === "sample" ? sample : input
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