-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12_pt1.js
55 lines (52 loc) · 1.39 KB
/
day12_pt1.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 input = require("fs")
.readFileSync("day12_input.txt")
.toString()
.split(/\r?\n/)
const parsedInput = []
//initiate graph
let graph = {}
//parse each input line
for (let i = 0; i < input.length; i++) {
let arr = input[i].split(" ")
for (let j = 0; j < arr.length; j++) {
//ignore the arrows
if (j === 0) {
if (graph[arr[j]] === undefined) {
graph[arr[j]] = []
}
} else if (j === 1) {
// do nothing
} else {
arr[j].replace(",", "")
arr[j] = parseInt(arr[j])
graph[arr[0]].push(arr[j])
}
}
}
console.log({ graph })
const programPrompt = 0
const answerArray = []
const checked = []
let stack = [...graph[programPrompt]]
console.log({ stack })
while (stack.length > 0) {
// console.log({ stack })
// console.log({ answerArray })
// check the first item in the stack, if it is already in the answerArr, ignore
if (!answerArray.includes(stack[0])) {
// if it isn't, then push to answer array
answerArray.push(stack[0])
// push its children, but ignore if already in stack or if equal to parent
graph[stack[0]].forEach((x) => {
if (x !== stack[0] && !stack.includes(x) && !checked.includes(x)) {
stack.push(x)
}
checked.push(x)
})
}
//remove from stack
stack.shift()
}
console.log(
`This answer is there are ${answerArray.length} programs connected to program ${programPrompt}`
)