diff --git a/days/src/main/kotlin/Day08.kt b/days/src/main/kotlin/Day08.kt index d3891c3..415e92f 100644 --- a/days/src/main/kotlin/Day08.kt +++ b/days/src/main/kotlin/Day08.kt @@ -10,22 +10,21 @@ import org.eclipse.collections.impl.factory.primitive.IntSets @Day(8) class Day08(@Lines val input: Input>) { - private val instructions = input.value - .map { - val words = it.split(" ") - Instruction(Operation.valueOf(words[0].capitalize()), words[1].toInt()) - }.toTypedArray() + private val instructions = input.value.map { + val words = it.split(" ") + Instruction(Operation.valueOf(words[0].capitalize()), words[1].toInt()) + }.toTypedArray() fun part1() = run(instructions) - private fun run(mutatedInstructions: Array): Int { + private fun run(instructions: Array): VmResult { var acc = 0 var ptr = 0 val visited = IntSets.mutable.empty() while (visited.add(ptr)) { - val instruction = mutatedInstructions[ptr] + val instruction = instructions[ptr] when (instruction.operation) { Operation.Acc -> { acc += instruction.argument @@ -34,28 +33,31 @@ class Day08(@Lines val input: Input>) { Operation.Jmp -> ptr += instruction.argument Operation.Nop -> ptr++ } - if (ptr !in mutatedInstructions.indices) { - println(acc) - error("oob") + if (ptr !in instructions.indices) { + return VmResult.Terminated(acc) } } - return acc + return VmResult.Looped(acc) } - fun part2() { + fun part2(): VmResult { val possibleMutations = IntLists.mutable.empty() instructions.forEachIndexed { i, e -> - if (e.operation != Operation.Acc) possibleMutations.add(i) + if (e.operation == Operation.Jmp || e.operation == Operation.Nop) possibleMutations.add(i) } - possibleMutations.forEach { index -> + for (index in possibleMutations.toArray()) { val copy = instructions.clone().also { val modifiedOperation = if (it[index].operation == Operation.Nop) Operation.Jmp else Operation.Nop it[index] = it[index].copy(operation = modifiedOperation) } - run(copy) + + val res = run(copy) + if (res is VmResult.Terminated) return res } + + error("No result found") } } @@ -64,6 +66,11 @@ enum class Operation { Acc, Jmp, Nop } data class Instruction(val operation: Operation, val argument: Int) +sealed class VmResult { + data class Looped(val acc: Int) : VmResult() + data class Terminated(val acc: Int) : VmResult() +} + fun main() { val day = createDay() println(day.part1())