Created
December 8, 2020 17:25
-
-
Save Shakezulla57/7a43ed4c339e729d30339ae8939fa394 to your computer and use it in GitHub Desktop.
adventofcode8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File | |
fun day8() { | |
val input = File("8.txt").readLines().map { it.trim() }.map { | |
parseInput(it) | |
} | |
val corrupted = findCorruptedIndex(input) | |
println("corrupted: $corrupted") | |
corrupted.forEach { | |
val accumulator = runProgram(input, it) | |
if (accumulator != 0) { | |
println(accumulator) | |
} | |
} | |
} | |
fun runProgram(instructions: List<Instruction>, corruptedIndex: Int): Int { | |
val ranIndexes = mutableSetOf<Int>() | |
var accumulatar: Int = 0 | |
var nextIndex = 0 | |
do { | |
ranIndexes.add(nextIndex) | |
val instruction = if (nextIndex == corruptedIndex) { | |
val corrupted = instructions[nextIndex] | |
when (corrupted.op) { | |
Op.nop -> { | |
Instruction(Op.jmp, corrupted.value) | |
} | |
else -> { | |
Instruction(Op.nop, corrupted.value) | |
} | |
} | |
} else { | |
instructions[nextIndex] | |
} | |
when (instruction.op) { | |
Op.acc -> { | |
accumulatar += instruction.value | |
nextIndex += 1 | |
} | |
Op.jmp -> nextIndex += instruction.value | |
Op.nop -> nextIndex += 1 | |
} | |
} while (nextIndex <= instructions.lastIndex && !ranIndexes.contains(nextIndex)) | |
return if (ranIndexes.contains(nextIndex)) 0 else accumulatar | |
} | |
fun findCorruptedIndex(instructions: List<Instruction>): List<Int> { | |
val ranIndexes = mutableSetOf<Int>() | |
var nextIndex = 0 | |
do { | |
ranIndexes.add(nextIndex) | |
val instruction = instructions[nextIndex] | |
nextIndex += when (instruction.op) { | |
Op.acc -> 1 | |
Op.jmp -> instruction.value | |
Op.nop -> 1 | |
} | |
println(nextIndex) | |
} while (!ranIndexes.contains(nextIndex)) | |
return ranIndexes.filter { | |
val op = instructions[it].op | |
op == Op.nop || op == Op.jmp | |
} | |
} | |
fun parseInput(input: String): Instruction { | |
return input.split(" ").let { | |
Instruction(Op.valueOf(it[0]), it[1].toInt(10)) | |
} | |
} | |
data class Instruction(val op: Op, val value: Int) | |
enum class Op { | |
acc, | |
jmp, | |
nop | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment