Nir
12/08/2020, 8:01 PMNir
12/08/2020, 8:01 PMenum class InstructionType {
JMP,
NOP,
ACC
}
data class Instruction(val type: InstructionType, val arg: Int)
fun getData() = (aocDataDir / "day8.txt").useLines { lines ->
lines.map{ line ->
val (typeStr, argStr) = line.split(" ")
val type = when (typeStr) {
"jmp" -> InstructionType.JMP
"nop" -> InstructionType.NOP
"acc" -> InstructionType.ACC
else -> throw Exception("Bad data!")
}
Instruction(type, argStr.toInt())
}.toList()
}
data class State(val accumulator: Int, val index: Int)
fun execute(program: List<Instruction>, state: State): State {
val instr = program[state.index]
return when (instr.type) {
InstructionType.JMP -> state.copy(index = state.index + instr.arg)
InstructionType.NOP -> state.copy(index = state.index + 1)
InstructionType.ACC -> state.copy(index = state.index + 1, accumulator = state.accumulator + instr.arg)
}
}
fun part2Fast(): Int {
val program = getData()
var flipState: State? = null
var currentState = State(0, 0)
val visited = mutableSetOf<Int>()
while (true) {
visited += currentState.index
if (flipState != null) {
currentState = execute(program, currentState)
if (currentState.index == program.size) {
return currentState.accumulator
}
if (currentState.index in visited) {
currentState = execute(program, flipState)
flipState = null
}
continue
}
val instr = program[currentState.index]
if (instr.type != InstructionType.ACC) {
flipState = currentState
}
currentState = when (instr.type) {
InstructionType.ACC -> currentState.copy(accumulator = currentState.accumulator + instr.arg, index = currentState.index + 1)
InstructionType.JMP -> currentState.copy(index = currentState.index + 1)
InstructionType.NOP -> currentState.copy(index = currentState.index + instr.arg)
}
}
}
bjonnh
12/08/2020, 8:40 PMNir
12/08/2020, 8:53 PMNir
12/08/2020, 8:53 PMNir
12/08/2020, 8:54 PMNir
12/08/2020, 9:02 PMbjonnh
12/08/2020, 9:11 PMbjonnh
12/08/2020, 9:12 PMNir
12/08/2020, 9:12 PMNir
12/08/2020, 9:12 PMNir
12/08/2020, 9:12 PMbjonnh
12/08/2020, 9:12 PMbjonnh
12/08/2020, 9:12 PMNir
12/08/2020, 9:13 PMNir
12/08/2020, 9:13 PMNir
12/08/2020, 9:13 PM