Public
Edited
Dec 18, 2021
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
return input
.match(/target area: x=(\d+)..(\d+), y=(-?\d+)..(-?\d+)/)
.slice(1, 5)
.map(Number);
}
Insert cell
Insert cell
Insert cell
function yPos(vy, nSteps) {
const n = nSteps + 1;
return (n * n) / -2 + ((2 * vy + 3) * n) / 2 - (vy + 1);
}
Insert cell
Insert cell
function hitsTargetY(vy, tBottom, tTop) {
let n = 0;
while (yPos(vy, ++n) > tTop) {}
return yPos(vy, n) >= tBottom;
}
Insert cell
Insert cell
function maxVy([tLeft, tRight, tBottom, tTop]) {
let vy = 100;
while (!hitsTargetY(vy, tBottom, tTop)) {
vy--;
}
return vy;
}
Insert cell
Insert cell
function part1(input) {
const vy = maxVy(parse(input));
return yPos(vy, Math.floor((2 * vy + 3) / 2));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function triangular(n) {
return (n * (n + 1)) / 2;
}
Insert cell
function xPos(vx, nSteps) {
const maxX = triangular(vx);
return nSteps < vx ? maxX - triangular(vx - nSteps) : maxX;
}
Insert cell
Insert cell
function hitsTarget(vx, vy, [tLeft, tRight, tBottom, tTop]) {
let n = 0;
// Advance enough to align with top of target
while (yPos(vy, ++n) > tTop) {}

// Continue to advance until we land inside target or we are below bottom.
let [x, y] = [xPos(vx, n), yPos(vy, n)];
while (y >= tBottom) {
if (x >= tLeft && x <= tRight) {
return 1;
}
n++;
[x, y] = [xPos(vx, n), yPos(vy, n)];
}
return 0;
}
Insert cell
Insert cell
function part2(input) {
const [tLeft, tRight, tBottom, tTop] = parse(input);
let numHits = 0;
let vxMin = 1;
while (triangular(++vxMin) < tLeft) {}

for (let vy = tBottom; vy <= maxVy([tLeft, tRight, tBottom, tTop]); vy++) {
for (let vx = vxMin; vx <= tRight; vx++) {
numHits += hitsTarget(vx, vy, [tLeft, tRight, tBottom, tTop]);
}
}
return numHits;
}
Insert cell
Insert cell
Insert cell
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