Published
Edited
Dec 17, 2021
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
part2 = results.filter(d => d.last.within).length
Insert cell
part1 = d3.max(
results.filter((d) => d.last.within),
(d) => d.last.max
)
Insert cell
results = d3
.cross(d3.range(1, target.x2 + 2), d3.range(target.y1 - 1, -target.y1 + 1))
.map(([vx, vy]) => ({ vx, vy, last: d3.reduce(launch(vx, vy), (_, d) => d) }))
Insert cell
function* launch(vx, vy) {
let state = {x: 0, y: 0, vx, vy};
let max = state.y;
let n = 0;
while (!inRange(state) && state.y >= target.y1) {
state = step(state);
if (state.y > max) max = state.y;
yield { n: ++n, state };
}
yield { n, state, within: inRange(state), max };
}
Insert cell
step = ({ x, y, vx, vy }) => ({
x: x + vx,
y: y + vy,
vx: vx - Math.sign(vx),
vy: vy - 1
})
Insert cell
inRange = ({ x, y }) =>
target.x1 <= x && x <= target.x2 && target.y1 <= y && y <= target.y2
Insert cell
target = {
const [x1, x2, y1, y2] = (which === "test" ? test : input)
.match(/x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)/)
.slice(1)
.map(Number);
return { x1, x2, y1, y2 };
}
Insert cell
test = `target area: x=20..30, y=-10..-5`
Insert cell
input = `target area: x=209..238, y=-86..-59`
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