RosettaCodeData/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy

45 lines
1.5 KiB
Groovy
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
class BrainfuckProgram {
def program = '', memory = [:]
def instructionPointer = 0, dataPointer = 0
def execute() {
2017-09-23 10:01:46 +02:00
while (instructionPointer < program.size())
2013-10-27 22:24:23 +00:00
switch(program[instructionPointer++]) {
case '>': dataPointer++; break;
case '<': dataPointer--; break;
2017-09-23 10:01:46 +02:00
case '+': memory[dataPointer] = memoryValue + 1; break
case '-': memory[dataPointer] = memoryValue - 1; break
case ',': memory[dataPointer] = System.in.read(); break
case '.': print String.valueOf(Character.toChars(memoryValue)); break
case '[': handleLoopStart(); break
case ']': handleLoopEnd(); break
2013-10-27 22:24:23 +00:00
}
}
private getMemoryValue() { memory[dataPointer] ?: 0 }
private handleLoopStart() {
if (memoryValue) return
2017-09-23 10:01:46 +02:00
int depth = 1
while (instructionPointer < program.size())
2013-10-27 22:24:23 +00:00
switch(program[instructionPointer++]) {
2017-09-23 10:01:46 +02:00
case '[': depth++; break
case ']': if (!(--depth)) return
2013-10-27 22:24:23 +00:00
}
throw new IllegalStateException('Could not find matching end bracket')
}
private handleLoopEnd() {
int depth = 0
while (instructionPointer >= 0) {
switch(program[--instructionPointer]) {
2017-09-23 10:01:46 +02:00
case ']': depth++; break
case '[': if (!(--depth)) return; break
2013-10-27 22:24:23 +00:00
}
}
throw new IllegalStateException('Could not find matching start bracket')
}
}