Jump to content

Execute Brain****/D: Difference between revisions

Version 2 D updated
(Version 1 updated)
(Version 2 D updated)
Line 99:
}</lang>
 
== Implementation=Version 2 ===
Alternative version, simplerSimpler and faster:
<lang d>import core.stdc.stdio: getchar, putchar, EOFcore.stdc.stdlib;
import core.stdc.stdlib: exit;
 
void brainfuckRun(constin string code) nothrow {
static pure int[int] matchBraces(constin string code) pure nothrow
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;
}
 
assert(!loopStack.length);
static void runCode(const string code, const int[int] loops) {
return loops;
}
 
static void runCode(constin string code, constin int[int] loops) nothrow {
enum char empty = '\0';
char[30_000] tape = empty;
Line 146 ⟶ 145:
case '.': putchar(tape[cell]); break;
case ',':
immutable int c = getchar();
if (c == EOF)
exit(1);
Line 159 ⟶ 158:
index = loops[index];
break;
default: break;
} break;
}
 
Line 172:
void main() {
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-]
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
+++.------.--------.>+.>.");
}</lang>
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.