Python
def brainfuck_interpreter(code):
tape = [0] * 30000
pointer = 0
output = ""
brackets = find_brackets(code)
code_ptr = 0
while code_ptr < len(code):
instruction = code[code_ptr]
if instruction == ">":
pointer += 1
elif instruction == "<":
pointer -= 1
elif instruction == "+":
tape[pointer] += 1
elif instruction == "-":
tape[pointer] -= 1
elif instruction == ".":
output += chr(tape[pointer])
elif instruction == ",":
tape[pointer] = ord(input()[:1])
elif instruction == "[" and tape[pointer] == 0:
code_ptr = brackets[code_ptr]
elif instruction == "]" and tape[pointer] != 0:
code_ptr = brackets[code_ptr]
code_ptr += 1
return output
def find_brackets(code):
brackets = {}
stack = []
for i, char in enumerate(code):
if char == "[":
stack.append(i)
elif char == "]":
open_bracket = stack.pop()
brackets[open_bracket] = i
brackets[i] = open_bracket
return brackets
bf_code = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+.>++++++++++."
output = brainfuck_interpreter(bf_code)
print(output)
C
#include <stdio.h>
#define MEMORY_SIZE 30000
void brainfuck_interpreter(char *code) {
char memory[MEMORY_SIZE] = {0};
char* ptr = memory;
while (*code != '\0') {
switch (*code) {
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++(*ptr);
break;
case '-':
--(*ptr);
break;
case '.':
putchar(*ptr);
break;
case ',':
*ptr = getchar();
break;
case '[':
if (*ptr == 0) {
int loop_count = 1;
while (loop_count > 0) {
++code;
if (*code == '[') {
++loop_count;
} else if (*code == ']') {
--loop_count;
}
}
}
break;
case ']':
if (*ptr != 0) {
int loop_count = 1;
while (loop_count > 0) {
--code;
if (*code == ']') {
++loop_count;
} else if (*code == '[') {
--loop_count;
}
}
}
break;
}
++code;
}
}
int main() {
char bf_code[] = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+.>++++++++++.";
brainfuck_interpreter(bf_code);
return 0;
}
C++
#include <iostream>
#define MEMORY_SIZE 30000
void brainfuck_interpreter(char* code) {
char memory[MEMORY_SIZE] = { 0 };
char* ptr = memory;
while (*code != '\0') {
switch (*code) {
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++(*ptr);
break;
case '-':
--(*ptr);
break;
case '.':
std::cout << *ptr;
break;
case ',':
std::cin >> *ptr;
break;
case '[':
if (*ptr == 0) {
int loop_count = 1;
while (loop_count > 0) {
++code;
if (*code == '[') {
++loop_count;
}
else if (*code == ']') {
--loop_count;
}
}
}
break;
case ']':
if (*ptr != 0) {
int loop_count = 1;
while (loop_count > 0) {
--code;
if (*code == ']') {
++loop_count;
}
else if (*code == '[') {
--loop_count;
}
}
}
break;
}
++code;
}
}
int main() {
char bf_code[] = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+.>++++++++++.";
brainfuck_interpreter(bf_code);
return 0;
}