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

Content added Content deleted
(Version 1 updated)
(Version 2 D updated)
Line 99: Line 99:
}</lang>
}</lang>


== Implementation 2 ==
===Version 2===
Alternative version, simpler and faster:
Simpler and faster:
<lang d>import core.stdc.stdio: getchar, putchar, EOF;
<lang d>import core.stdc.stdio, core.stdc.stdlib;
import core.stdc.stdlib: exit;


void brainfuckRun(const string code) {
void brainfuckRun(in string code) nothrow {
static pure int[int] matchBraces(const string code)
static int[int] matchBraces(in string code) pure nothrow
out(result) {
out(result) {
foreach (k, v; result) {
foreach (k, v; result) {
assert(k >=0 && k < code.length);
assert(k >=0 && k < code.length);
assert(v >=0 && v < code.length);
assert(v >=0 && v < code.length);
assert(v in result);
assert(v in result);
}
}
} body {
} body {
int[int] loops;
int[int] loops;
int[] loopStack;
int[] loopStack;


foreach (i, instruction; code) {
foreach (i, instruction; code) {
if (instruction == '[')
if (instruction == '[')
loopStack ~= i;
loopStack ~= i;
else if (instruction == ']') {
else if (instruction == ']') {
assert(loopStack.length);
assert(loopStack.length);
loops[i] = loopStack[$ - 1];
loops[i] = loopStack[$ - 1];
loopStack.length -= 1;
loopStack.length -= 1;
loops[loops[i]] = i;
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(in string code, in int[int] loops) nothrow {
enum char empty = '\0';
enum char empty = '\0';
char[30_000] tape = empty;
char[30_000] tape = empty;
Line 146: Line 145:
case '.': putchar(tape[cell]); break;
case '.': putchar(tape[cell]); break;
case ',':
case ',':
int c = getchar();
immutable int c = getchar();
if (c == EOF)
if (c == EOF)
exit(1);
exit(1);
Line 159: Line 158:
index = loops[index];
index = loops[index];
break;
break;
default: break;
default:
break;
}
}


Line 172: Line 172:
void main() {
void main() {
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-]
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-]
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.
+++.------.--------.>+.>.");
}</lang>
}</lang>