1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-19 14:16:55 +02:00
CodeWars/5kyu/simple_assembler_interpreter/solution.kt

39 lines
1.2 KiB
Kotlin
Raw Normal View History

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
}