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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more