|
|
@@ -0,0 +1,73 @@
|
|
|
+package de.doriansnowball.adventofcode
|
|
|
+
|
|
|
+import java.io.File
|
|
|
+
|
|
|
+fun main() {
|
|
|
+ solvePuzzle8()
|
|
|
+}
|
|
|
+
|
|
|
+fun solvePuzzle8() {
|
|
|
+ val opLines = File("puzzleInput/day8-1.txt").readLines()
|
|
|
+ val operations = mutableListOf<Operation>()
|
|
|
+
|
|
|
+ for (opString in opLines) {
|
|
|
+ val split = opString.split(' ')
|
|
|
+ operations.add(Operation(OperationType.valueOf(split[0].toUpperCase()), split[1].toInt()))
|
|
|
+ }
|
|
|
+
|
|
|
+ // execute
|
|
|
+ var accumulator: Int = 0
|
|
|
+
|
|
|
+ for (op in operations) {
|
|
|
+ if (op.opType == OperationType.JMP) {
|
|
|
+ op.opType = OperationType.NOP
|
|
|
+ val result = execute(operations, accumulator)
|
|
|
+ if (result != Int.MIN_VALUE) {
|
|
|
+ accumulator = result
|
|
|
+ break
|
|
|
+ }
|
|
|
+ op.opType = OperationType.JMP
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+// accumulator = execute(operations, accumulator)
|
|
|
+
|
|
|
+ println("Accumulator is $accumulator")
|
|
|
+}
|
|
|
+
|
|
|
+private fun execute(operations: MutableList<Operation>, accumulator: Int): Int {
|
|
|
+ var accumulator1 = accumulator
|
|
|
+ var currentOp = operations[0]
|
|
|
+ var activeLine = 0
|
|
|
+ val executedOps = mutableListOf<Operation>()
|
|
|
+
|
|
|
+ while (true) {
|
|
|
+ when (currentOp.opType) {
|
|
|
+ OperationType.ACC -> {
|
|
|
+ accumulator1 += currentOp.argument
|
|
|
+ activeLine++
|
|
|
+ }
|
|
|
+ OperationType.JMP -> activeLine += currentOp.argument
|
|
|
+ OperationType.NOP -> activeLine++
|
|
|
+ }
|
|
|
+ executedOps.add(currentOp)
|
|
|
+ if (activeLine == operations.size) {
|
|
|
+ println("Finished running program")
|
|
|
+ break
|
|
|
+ }
|
|
|
+
|
|
|
+ currentOp = operations[activeLine]
|
|
|
+
|
|
|
+ if (executedOps.contains(currentOp)) {
|
|
|
+ return Int.MIN_VALUE;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return accumulator1
|
|
|
+}
|
|
|
+
|
|
|
+class Operation(var opType: OperationType, val argument: Int)
|
|
|
+
|
|
|
+enum class OperationType {
|
|
|
+ ACC, JMP, NOP
|
|
|
+}
|
|
|
+
|