-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.kt
71 lines (67 loc) · 1.98 KB
/
main.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.File
import java.io.FileNotFoundException
import java.util.*
import kotlin.collections.HashMap
fun parseCycles(instructions: List<String>): HashMap<Int, Int> {
val brackets = HashMap<Int, Int>()
val stack = Stack<Int>()
for ((i, instruction) in instructions.withIndex()) {
if (instruction == "MOO") {
stack.push(i)
} else if (instruction == "moo") {
if (stack.empty()) {
throw Exception("Wrong expression")
} else {
val start = stack.pop()
brackets[i] = start
brackets[start] = i
}
}
}
return brackets
}
fun run(source: String) {
val instructions = source.split("\\s+".toRegex())
val memory = Array(20000){0}
var ptr = 0;
var i = 0;
var register = 0;
var save = false;
val brackets = parseCycles(instructions)
while (i != instructions.size) {
when (instructions[i]) {
"MoO" -> memory[ptr] = memory[ptr] + 1
"MOo" -> memory[ptr] = memory[ptr] - 1
"moO" -> ptr++
"mOo" -> ptr--
"OOM" -> print(memory[ptr])
"oom" -> memory[ptr] = readLine()?.toInt()!!
"OOO" -> memory[ptr] = 0
"Moo" -> if (memory[ptr] == 0) memory[ptr]=readLine()?.toInt()!! else print(memory[ptr].toChar())
"MMM" -> {
if (save) memory[ptr] = register else register = memory[ptr]
save = !save
}
"MOO" -> {
if (memory[ptr] == 0) {
i = brackets[i]!!
}
}
"moo" -> {
if (memory[ptr] != 0) {
i = brackets[i]!!
}
}
}
i++;
}
}
fun main() {
val filename = readLine()
try {
val source = File(filename).readText().trim()
run(source)
} catch (e: FileNotFoundException) {
print("File not found")
}
}