-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay8_2.ws.kts
45 lines (34 loc) · 1.04 KB
/
Day8_2.ws.kts
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
val input = java.io.File("D:/GitHub/pavi2410/AdventOfCode2020-KT/inputs/Day8.txt").readLines()
fun run(instructions: List<String>): Pair<Boolean, Int> {
var pc = 0
var acc = 0
val visitedLines = mutableListOf<Int>()
while (pc < instructions.size) {
if (pc in visitedLines) return false to acc
visitedLines += pc
val (opcode, arg) = instructions[pc].split(" ")
when (opcode) {
"acc" -> {
acc += arg.toInt()
pc++
}
"jmp" -> pc += arg.toInt()
"nop" -> pc++
}
}
return true to acc
}
fun flip(inst: String) = if (inst.startsWith("jmp")) inst.replace("jmp", "nop") else inst.replace("nop", "jmp")
var output = 0
for ((i, l) in input.withIndex()) {
if (l.take(3) !in listOf("jmp", "nop")) continue
val newInput = input.toMutableList().apply {
this[i] = flip(this[i])
}
val (terminated, acc) = run(newInput)
if (terminated) {
output = acc
break
}
}
println(output) // 2212