Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
tpatel committed Dec 17, 2021
1 parent e80bcad commit 6ec140f
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
69 changes: 69 additions & 0 deletions day17.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const fs = require("fs");

const line = fs
.readFileSync("day17.txt", { encoding: "utf-8" }) // read day??.txt content
.trim();

const target = line.match(
/target area: x=(?<xMin>-?\d+)..(?<xMax>-?\d+), y=(?<yMin>-?\d+)..(?<yMax>-?\d+)/
).groups;

function simulate({ vx, vy, target }) {
const steps = [];
let x = 0;
let y = 0;
while (x < target.xMax && y > target.yMin) {
steps.push({ x, y });
x += vx;
y += vy;
if (vx > 0) {
vx--;
}
if (vx < 0) {
vx++;
}
vy--; //gravity
if (
x >= target.xMin &&
x <= target.xMax &&
y >= target.yMin &&
y <= target.yMax
) {
steps.push({ x, y });
return steps;
}
}
}

function part1() {
let maxY = 0;
for (let vx = 0; vx < target.xMax; vx++) {
for (let vy = 1000; vy >= 0; vy--) {
const steps = simulate({ vx, vy, target });
if (steps) {
let max = Math.max(...steps.map((p) => p.y));
if (max > maxY) {
maxY = max;
}
}
}
}
console.log(maxY);
}

part1();

function part2() {
let total = 0;
for (let vx = 1; vx <= target.xMax; vx++) {
for (let vy = 1000; vy >= target.yMin; vy--) {
const steps = simulate({ vx, vy, target });
if (steps) {
total++;
}
}
}
console.log(total);
}

part2();
1 change: 1 addition & 0 deletions day17.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
target area: x=150..193, y=-136..-86

0 comments on commit 6ec140f

Please sign in to comment.