Skip to content

Instantly share code, notes, and snippets.

@cycadacka
Last active April 11, 2020 10:36
Show Gist options
  • Save cycadacka/9c16ad62046993a77289e71af3cf57b0 to your computer and use it in GitHub Desktop.
Save cycadacka/9c16ad62046993a77289e71af3cf57b0 to your computer and use it in GitHub Desktop.
Brainfudge Interpreter
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void Interpret(string input, vector<uint8_t> &memory);
int main()
{
vector<uint8_t> memory{ 0 };
string input;
getline(cin, input);
Interpret(input, memory);
}
void Interpret(string input, vector<uint8_t> &memory)
{
vector<unsigned int> loops;
int pointer = 0;
for (size_t i = 0; i < input.length(); ++i) {
char c = input[i];
switch (c) {
case '>':
if (++pointer > memory.size() - 1) {
memory.push_back(0);
}
break;
case '<':
if (--pointer < 0) {
cout << "Error";
return;
}
break;
case '+':
++memory[pointer];
break;
case '-':
--memory[pointer];
break;
case '.':
cout << (char) memory[pointer];
break;
case ',':
char programInput;
cin >> programInput;
memory[pointer] = (uint8_t) programInput;
break;
case '[':
if (memory[pointer] == 0) {
unsigned int simLoops = 1;
unsigned int simIndex = i + 1;
while (simLoops > 0 && simIndex < input.length()) {
char a = input[simIndex];
if (a == ']') {
simLoops--;
} else if (a == '[') {
simLoops++;
}
simIndex++;
}
i = simIndex - 1;
} else {
loops.push_back(i);
}
break;
case ']':
if (loops.size() > 0) {
if (memory[pointer] == 0) {
loops.pop_back();
} else {
i = loops[loops.size() - 1];
}
}
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment