-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday08_pt2.js
89 lines (87 loc) · 2.56 KB
/
day08_pt2.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
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
let max = 0
// creating functions that allows us to turn a string compartor into and evaluative comparison statement, returns t/f
const executeComparator = {
">": function (x, y) {
return x > y
},
">=": function (x, y) {
return x >= y
},
"<": function (x, y) {
return x < y
},
"<=": function (x, y) {
return x <= y
},
"==": function (x, y) {
return x === y
},
"!=": function (x, y) {
return x !== y
},
}
//parsing the input given by the puzzle into an array with an item for each line
const input = require("fs")
.readFileSync("day08_input.txt")
.toString()
.split(/\r?\n/)
//mapping our instructions into an array of objects, with properties that will allow us to execute the instructions.
const instructions = input.map((line) => {
let splitLine = line.split(" ")
return {
register: splitLine[0],
operator: splitLine[1],
delta: parseInt(splitLine[2]),
conditionRegister: splitLine[4],
conditionCompartor: splitLine[5],
conditionComparee: parseInt(splitLine[6]),
}
})
// creating an empty object to track registers
let registers = {}
//going through each instruction line and executing
for (const line of instructions) {
//console.log(line)
//check if condition is true
let conditionRegisterValue = returnRegisterValue(
line.conditionRegister,
registers
)
let conditionMet = executeComparator[line.conditionCompartor](
conditionRegisterValue,
line.conditionComparee
)
if (conditionMet) {
let registerValue = returnRegisterValue(line.register, registers)
if (line.operator === "inc") {
registers[line.register] = registerValue + line.delta
} else {
registers[line.register] = registerValue - line.delta
}
if (registers[line.register] > max) {
max = registers[line.register]
}
//console.log(`executing ${line.register} ${line.operator} ${line.delta}`)
}
}
let valuesOfRegisters = []
for (const register in registers) {
valuesOfRegisters.push(registers[register])
}
valuesOfRegisters.sort((a, b) => b - a)
//console.log({ registers })
//console.log({ valuesOfRegisters })
console.log(`the answer is ${max}`)
function returnRegisterValue(regName, registersObj) {
if (registersObj.hasOwnProperty(regName)) {
/*console.log(
`${regName} register exists, it's value is ${registersObj[regName]}`
)*/
} else {
registersObj[regName] = 0
//console.log(`register does not exist, creating register ${regName}`)
//console.log({ registers })
}
return registersObj[regName]
}
//console.log(countRegisterCreation, valuesOfRegisters.length)