mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 19:19:07 +01:00
39 lines
1.2 KiB
Kotlin
39 lines
1.2 KiB
Kotlin
|
private fun constantOrRegister(token: String, regs: Map<String, Int>): Int =
|
||
|
token.toIntOrNull() ?: regs.getOrDefault(token, 0)
|
||
|
|
||
|
fun interpret(program: Array<String>): Map<String, Int> {
|
||
|
var result = mutableMapOf<String, Int>()
|
||
|
var instruction = 0
|
||
|
|
||
|
while (instruction in program.indices) {
|
||
|
val ops = program.elementAt(instruction).split(' ')
|
||
|
|
||
|
when (ops[0]) {
|
||
|
"mov" -> {
|
||
|
val value = constantOrRegister(ops[2], result)
|
||
|
result.put(ops[1], value)
|
||
|
}
|
||
|
"inc" -> {
|
||
|
val value = result.getOrDefault(ops[1], 0)
|
||
|
result.put(ops[1], value + 1)
|
||
|
}
|
||
|
"dec" -> {
|
||
|
val value = result.getOrDefault(ops[1], 0)
|
||
|
result.put(ops[1], value - 1)
|
||
|
}
|
||
|
"jnz" -> {
|
||
|
val diff = constantOrRegister(ops[2], result)
|
||
|
val cond = constantOrRegister(ops[1], result)
|
||
|
|
||
|
if (cond != 0) {
|
||
|
instruction = instruction + diff - 1
|
||
|
}
|
||
|
}
|
||
|
else -> error("invalid instruction")
|
||
|
}
|
||
|
instruction++
|
||
|
}
|
||
|
|
||
|
return result
|
||
|
}
|