Execute Brain****/D: Difference between revisions
Content added Content deleted
(Version 1 updated) |
(Version 2 D updated) |
||
Line 99: | Line 99: | ||
}</lang> |
}</lang> |
||
== |
===Version 2=== |
||
Simpler and faster: |
|||
<lang d>import core.stdc.stdio |
<lang d>import core.stdc.stdio, core.stdc.stdlib; |
||
import core.stdc.stdlib: exit; |
|||
void brainfuckRun( |
void brainfuckRun(in string code) nothrow { |
||
static |
static int[int] matchBraces(in 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; |
|||
⚫ | |||
} |
} |
||
⚫ | |||
⚫ | |||
} |
} |
||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
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: |
default: |
||
⚫ | |||
} |
} |
||
Line 172: | Line 172: | ||
void main() { |
void main() { |
||
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-] |
brainfuckRun("++++++++++[>+++++++>++++++++++>+++>+<<<<-] |
||
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>. |
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>. |
||
+++.------.--------.>+.>."); |
|||
}</lang> |
}</lang> |
||