Skip to content

Commit fbcf2c5

Browse files
committed
Day 22 Part 1
1 parent e04e7b2 commit fbcf2c5

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

input/d22.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
depth: 10689
2+
target: 11,722

input/d22ex.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
depth: 510
2+
target: 10,10

src/d22.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
console.time("d22");
2+
const rl = require("./utils").getInputRL("d22");
3+
4+
let DEPTH;
5+
let TARGET; // {x, y}
6+
7+
let erosion_levels = {}; // `x,y`: erosionLevel
8+
9+
const ROCKY = 0;
10+
const WET = 1;
11+
const NARROW = 2;
12+
13+
function programReadLine(rl) {
14+
const depthRegex = /depth: (\d+)/;
15+
const depthTarget = /target: (\d+),(\d+)/;
16+
rl.on("line", line => {
17+
let depthMatch = depthRegex.exec(line);
18+
let targetMatch = depthTarget.exec(line);
19+
if (depthMatch) {
20+
DEPTH = Number(depthMatch[1]);
21+
} else if (targetMatch) {
22+
TARGET = {
23+
x: Number(targetMatch[1]),
24+
y: Number(targetMatch[2])
25+
};
26+
}
27+
});
28+
29+
rl.on("close", () => {
30+
console.log(DEPTH);
31+
console.log(TARGET);
32+
console.log("Answer (Part 1):", runPart1());
33+
console.log("Answer (Part 2):");
34+
console.timeEnd("d22");
35+
});
36+
}
37+
38+
function runPart1() {
39+
let sum = 0;
40+
for (let x = 0; x <= TARGET.x; x++) {
41+
for (let y = 0; y <= TARGET.y; y++) {
42+
sum += getErosionLevel(x, y) % 3;
43+
}
44+
}
45+
return sum;
46+
}
47+
48+
function getErosionLevel(x, y) {
49+
let xy = `${x},${y}`;
50+
let level = erosion_levels[xy];
51+
if (level === undefined) {
52+
level = (getGeologicIndex(x, y) + DEPTH) % 20183;
53+
erosion_levels[xy] = level;
54+
}
55+
return level;
56+
}
57+
58+
function getGeologicIndex(x, y) {
59+
if (x === 0 && y === 0) {
60+
return 0;
61+
}
62+
if (x === TARGET.x && y === TARGET.y) {
63+
return 0;
64+
}
65+
if (x === 0 || y === 0) {
66+
return x * 16807 + y * 48271;
67+
}
68+
return getErosionLevel(x - 1, y) * getErosionLevel(x, y - 1);
69+
}
70+
71+
programReadLine(rl);

0 commit comments

Comments
 (0)