40 lines
1.8 KiB
Kotlin
40 lines
1.8 KiB
Kotlin
|
import java.io.File
|
||
|
|
||
|
val instructionMap = mapOf(
|
||
|
"inc" to { left: Int, right: Int -> left + right},
|
||
|
"dec" to { left: Int, right: Int -> left - right }
|
||
|
)
|
||
|
val conditionMap = mapOf(
|
||
|
"==" to { left: Int, right: Int -> left == right },
|
||
|
"!=" to { left: Int, right: Int -> left != right },
|
||
|
">=" to { left: Int, right: Int -> left >= right },
|
||
|
"<=" to { left: Int, right: Int -> left <= right },
|
||
|
">" to { left: Int, right: Int -> left > right },
|
||
|
"<" to { left: Int, right: Int -> left < right }
|
||
|
)
|
||
|
data class Instruction(val register: String, val op: String, val operand: Int,
|
||
|
val conditionRegister: String, val condition: String, val conditionOperand: Int) {
|
||
|
fun execute(registers: MutableMap<String, Int>) {
|
||
|
if(conditionMap[condition]!!(registers.getOrDefault(conditionRegister, 0), conditionOperand))
|
||
|
registers[register] = instructionMap[op]!!(registers.getOrDefault(register, 0), operand)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun main(args: Array<String>) {
|
||
|
val registerMap = mutableMapOf<String, Int>()
|
||
|
val extractionPattern = Regex("([a-z]+) (inc|dec) (-?\\d+) if ([a-z]+) ([^\\s]+) (-?\\d+)")
|
||
|
val instructions = File("../puzzle_8.txt").readLines().map {
|
||
|
val resultingPattern = extractionPattern.matchEntire(it) ?: return
|
||
|
with(resultingPattern.groupValues){
|
||
|
Instruction(get(1), get(2), get(3).toInt(), get(4), get(5), get(6).toInt())
|
||
|
}
|
||
|
}
|
||
|
var maxValue = Int.MIN_VALUE
|
||
|
instructions.forEach {
|
||
|
it.execute(registerMap)
|
||
|
val currentMax = registerMap.values.sorted().last()
|
||
|
maxValue = Math.max(currentMax, maxValue)
|
||
|
}
|
||
|
println("Largest value in any register is ${registerMap.values.sorted().last()}")
|
||
|
println("Largest possible max value is $maxValue")
|
||
|
}
|