-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.ts
100 lines (72 loc) · 2.13 KB
/
8.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const fs = require('fs');
const readline = require('readline');
const math = require('mathjs');
const fileStream = fs.createReadStream('8-input.txt');
const path = "LRLRRRLRRRLLLRLRRLLRLRRRLRLRRRLRLRRRLRLRRRLRRRLRLLRRRLRLRLRRLRRLRLRRLRRLRRLLRRRLRRRLRRLRRLRRLRRRLLRRLRLRRLRLRRLRRLRLRRLRRLLRLRRRLRRLRRRLLRLRLRLLRLLRLLRLRRLLRRLRLRLRRLRLLRRRLLRRRLRRLLRRRLRRRLRLRRRLLRRRLRLRRRLLLRRRLRLRLRRRLRRRLRRRLRLRRLLLRRLRRRLLRLRRRLRLRLLLRRLRLRRRLRLRRRR";
const start = "AAA";
let starters = [];
let allSteps = [];
let pos = 0;
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let dictionary = {};
const findPath = () => {
let next = start;
let steps = 1;
while(true){
//console.log("Next: ", next, " dictionary: ", dictionary[next], " direction: ", path[pos], " pos: ", pos, " steps: ", steps)
if(path[pos] == 'L'){
next = dictionary[next][0]
}else{
next = dictionary[next][1]
}
if(next === 'ZZZ'){
console.log("Part one steps: ", steps)
break;
}
steps ++;
pos ++;
if(pos === path.length) pos = 0;
}
}
const findPath2 = (start) => {
let next = start;
let steps = 1;
let pos = 0;
while(true){
if(path[pos] == 'L'){
next = dictionary[next][0]
}else{
next = dictionary[next][1]
}
if(next.endsWith("Z")){
allSteps.push(steps)
break;
}
steps ++;
pos ++;
if(pos === path.length) pos = 0;
}
}
rl.on('line', (line) => {
let test = line.split('=');
let noekkel = test[0].trim()
let verdi = test[1].trim()
.replace("(", "")
.replace(")", "")
.split(", ")
dictionary[noekkel] = verdi;
if(noekkel.endsWith("A")){
starters.push(noekkel)
}
});
rl.on('close', () => {
findPath()
console.log("Starters part 2: ", starters)
starters.forEach((start) => {
findPath2(start)
})
console.log("Part 2 total steps: ", math.lcm(...allSteps))
});