Public
Edited
Dec 10, 2023
1 fork
4 stars
Insert cell
Insert cell
Insert cell
w = s.indexOf("\n") + 1
Insert cell
h = (s.length + 1) / w
Insert cell
index = ([x, y]) =>
0 <= x && x < w - 1 && 0 <= y && y < h ? y * w + x : undefined
Insert cell
coords = (i) => [i % w, Math.floor(i / w)]
Insert cell
start = coords(s.indexOf("S"))
Insert cell
connections = (p) => new d3.InternSet(tiles[s[index(p)]](p), String)
Insert cell
function* neighbors([x, y]) {
yield [x, y+1];
yield [x, y-1];
yield [x+1, y];
yield [x-1, y];
}
Insert cell
tiles = ({
"|": ([x, y]) => [[x, y-1], [x, y+1]],
"-": ([x, y]) => [[x-1, y], [x+1, y]],
"L": ([x, y]) => [[x, y-1], [x+1, y]],
"J": ([x, y]) => [[x, y-1], [x-1, y]],
"7": ([x, y]) => [[x-1, y], [x, y+1]],
"F": ([x, y]) => [[x+1, y], [x, y+1]],
".": () => [],
undefined: () => [],
"S": ([x, y]) => undefined,
})
Insert cell
function* parse() {
yield [start, 0];
const seen = new d3.InternSet([start], String);
const q = d3.filter(neighbors(start), (n) => connections(n).has(start)).map(p => [p, 1]);
while (q.length) {
const [p, d] = q.shift();
if (!seen.has(p)) {
seen.add(p);
yield [p, d];
}
for (const n of connections(p)) if (!seen.has(n)) q.push([n, d + 1]);
}
}
Insert cell
part1 = d3.greatest(parse(), d => d[1])
Insert cell
polygon = {
const points = d3.map(parse(), (d) => d[0]);
const evens = points.filter((d,i) => i % 2 === 0);
const odds = points.filter((d,i) => i % 2 === 1);
return evens.concat(odds.reverse());
}
Insert cell
part2 = {
const edge = new d3.InternSet(polygon, String);
const xs = d3.extent(polygon, (d) => d[0]);
const ys = d3.extent(polygon, (d) => d[1]);
const contained = new d3.InternSet([], String);
for (let x = xs[0]; x <= xs[1]; x++)
for (let y = ys[0]; y <= ys[1]; y++)
if (!edge.has([x, y]) && d3.polygonContains(polygon, [x, y]))
contained.add([x, y]);
return contained;
}
Insert cell
s = input
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