Public
Edited
Dec 15, 2022
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
part2 = (gap[0][1] + 1) * 4000000 + excluded
Insert cell
gap = [...union(xs(excluded))].sort((a, b) => a[0] - b[0])
Insert cell
excluded = {
for (let y = which === "sample" ? 0 : 2638000; y <= max; y++) {
if (y % 10000 === 0) yield y;
if (union(xs(y)).size > 1) {
yield y;
break;
}
}
}
Insert cell
part1 = d3.sum([...union(xs(max/2))].map(([x1, x2]) => x2 - x1 + 1)) - b.size
Insert cell
b = new Set(signals.filter(({ by }) => by === max / 2).map((d) => d.bx))
Insert cell
function union(xs) {
const disjoint = new d3.InternSet([], String);
for (const s of xs) {
const [s1, s2] = s;
const overlaps = [...disjoint].filter(([u1, u2]) => s2 >= u1 && u2 >= s1);
if (overlaps.length === 0) {
disjoint.add(s);
} else {
for (const o of overlaps) disjoint.delete(o);
const points = overlaps.flat().concat(s);
disjoint.add(d3.extent(points));
}
}
return disjoint;
}
Insert cell
intersection = (y) =>
([p1, p2]) => {
const m = (p2[1] - p1[1]) / (p2[0] - p1[0]);
const b = p1[1] - m * p1[0];
return (y - b) / m;
}
Insert cell
xs = (y) =>
coverages
.map((c) => edges(c).filter(intersects(y)))
.filter((e) => e.length)
.map((t) => t.slice(0, 2).map(intersection(y)).sort(d3.ascending))
Insert cell
edges = (polygon) => d3.pairs(polygon.concat([polygon[0]]))
Insert cell
intersects = (y) =>
([[, y1], [, y2]]) =>
Math.min(y1, y2) <= y && y <= Math.max(y1, y2)
Insert cell
coverages = signals.map(({ sx, sy, bx, by }) => {
const d = Math.abs(bx - sx) + Math.abs(by - sy);
return [
[sx - d, sy], // left
[sx, sy + d], // top
[sx + d, sy], // right
[sx, sy - d] // bottom
];
})
Insert cell
max = which === "sample" ? 20 : 4000000
Insert cell
signals = (which === "sample" ? sample : data)
.trim()
.split("\n")
.map((l) => {
const [, sx, sy, bx, by] = l.match(
/Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)/
);
return { sx: +sx, sy: +sy, bx: +bx, by: +by };
})
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