forked from tpatel/advent-of-code-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
target area: x=150..193, y=-136..-86 |