Clean a bit
This commit is contained in:
parent
7d8db7b493
commit
ee2dfbd40b
@ -10,22 +10,21 @@ import org.eclipse.collections.impl.factory.primitive.IntSets
|
||||
@Day(8)
|
||||
class Day08(@Lines val input: Input<List<String>>) {
|
||||
|
||||
private val instructions = input.value
|
||||
.map {
|
||||
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<Instruction>): Int {
|
||||
private fun run(instructions: Array<Instruction>): 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<List<String>>) {
|
||||
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<Day08>()
|
||||
println(day.part1())
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user