-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
55 lines (47 loc) · 1.27 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const fs = require("fs");
const gcd = (a, b) => (a ? gcd(b % a, a) : b);
const lcm = (a, b) => (a * b) / gcd(a, b);
const input = fs.readFileSync("input.txt", "utf8").trimEnd().split("\n");
const instructions = input[0];
const map = new Map();
let part1 = 0;
let start = "AAA";
let moves = [];
for (let i = 2; i < input.length; i++) {
const key = input[i].split("=")[0].trim();
const instructions = input[i].split("=")[1];
map.set(key, instructions);
}
let i = -1;
while (start !== "ZZZ") {
const move = instructions[++i % instructions.length];
const left = map.get(start).substring(2, 5);
const right = map.get(start).substring(7, 10);
if (move === "L") {
start = left;
} else {
start = right;
}
part1++;
}
for (const key of Array.from(map.keys())) {
if (key.endsWith("A")) {
let start = key;
let i = -1;
let totalMoves = 0;
while (!start.endsWith("Z")) {
const move = instructions[++i % instructions.length];
const left = map.get(start).substring(2, 5);
const right = map.get(start).substring(7, 10);
if (move === "L") {
start = left;
} else {
start = right;
}
totalMoves++;
}
moves.push(totalMoves);
}
}
console.log("part1: ", part1);
console.log('part2: ', moves.reduce(lcm));