Execute Brain****: Difference between revisions
Content added Content deleted
Line 122: | Line 122: | ||
[[/D|Implementation in D]]. |
[[/D|Implementation in D]]. |
||
Alternative version, simpler and faster. |
|||
<lang d>import core.stdc.stdio: getc, putchar, stdin, EOF; |
|||
import core.stdc.stdlib: exit; |
|||
void brainfuckRun(const string code) { |
|||
static pure int[int] matchBraces(const string code) |
|||
out(result) { |
|||
foreach (k, v; result) { |
|||
assert(k >=0 && k < code.length); |
|||
assert(v >=0 && v < code.length); |
|||
assert(v in result); |
|||
} |
|||
} body { |
|||
int[int] loops; |
|||
int[] loopStack; |
|||
foreach (i, instruction; code) { |
|||
if (instruction == '[') |
|||
loopStack ~= i; |
|||
else if (instruction == ']') { |
|||
assert(loopStack.length); |
|||
loops[i] = loopStack[$ - 1]; |
|||
loopStack.length -= 1; |
|||
loops[loops[i]] = i; |
|||
} |
|||
} |
|||
assert(!loopStack.length); |
|||
return loops; |
|||
} |
|||
static void runCode(const string code, const int[int] loops) { |
|||
enum char empty = '\0'; |
|||
char[30_000] tape = empty; |
|||
int cell, index; |
|||
while (index < cast(int)code.length) { |
|||
immutable int instruction = code[index]; |
|||
switch (instruction) { |
|||
case '>': cell++; assert(cell < tape.length); break; |
|||
case '<': cell--; assert(cell >= 0); break; |
|||
case '+': tape[cell]++; break; |
|||
case '-': tape[cell]--; break; |
|||
case '.': putchar(tape[cell]); break; |
|||
case ',': |
|||
int c = getc(stdin); |
|||
if (c == EOF) |
|||
exit(1); |
|||
tape[cell] = cast(char)c; |
|||
break; |
|||
case '[': |
|||
if (tape[cell] == empty) |
|||
index = loops[index]; |
|||
break; |
|||
case ']': |
|||
if (tape[cell] != empty) |
|||
index = loops[index]; |
|||
break; |
|||
default: break; |
|||
} |
|||
index++; |
|||
} |
|||
} |
|||
int[int] loops = matchBraces(code); |
|||
runCode(code, loops); |
|||
} |
|||
void main() { |
|||
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-] |
|||
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."); |
|||
}</lang> |
|||
=={{header|E}}== |
=={{header|E}}== |