Day08
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package be.vandewalleh.aoc.days
|
||||
|
||||
import be.vandewalleh.aoc.utils.input.Day
|
||||
import be.vandewalleh.aoc.utils.input.Input
|
||||
import be.vandewalleh.aoc.utils.input.Lines
|
||||
import be.vandewalleh.aoc.utils.input.createDay
|
||||
import org.eclipse.collections.impl.factory.primitive.IntLists
|
||||
import org.eclipse.collections.impl.factory.primitive.IntSets
|
||||
|
||||
@Day(8)
|
||||
class Day08(@Lines val input: Input<List<String>>) {
|
||||
|
||||
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 {
|
||||
var acc = 0
|
||||
var ptr = 0
|
||||
|
||||
val visited = IntSets.mutable.empty()
|
||||
|
||||
while (visited.add(ptr)) {
|
||||
val instruction = mutatedInstructions[ptr]
|
||||
when (instruction.operation) {
|
||||
Operation.Acc -> {
|
||||
acc += instruction.argument
|
||||
ptr++
|
||||
}
|
||||
Operation.Jmp -> ptr += instruction.argument
|
||||
Operation.Nop -> ptr++
|
||||
}
|
||||
if (ptr !in mutatedInstructions.indices) {
|
||||
println(acc)
|
||||
error("oob")
|
||||
}
|
||||
}
|
||||
|
||||
return acc
|
||||
}
|
||||
|
||||
fun part2() {
|
||||
val possibleMutations = IntLists.mutable.empty()
|
||||
instructions.forEachIndexed { i, e ->
|
||||
if (e.operation != Operation.Acc) possibleMutations.add(i)
|
||||
}
|
||||
|
||||
possibleMutations.forEach { index ->
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
enum class Operation { Acc, Jmp, Nop }
|
||||
|
||||
data class Instruction(val operation: Operation, val argument: Int)
|
||||
|
||||
fun main() {
|
||||
val day = createDay<Day08>()
|
||||
println(day.part1())
|
||||
println(day.part2())
|
||||
}
|
||||
Reference in New Issue
Block a user