1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/5kyu/simple_assembler_interpreter/solution.kt
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

38 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
}