Created
July 14, 2022 19:46
-
-
Save Atem2069/71b192ebe07f46c59207622ddc338e69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include<iostream> | |
#include<vector> | |
#include<stack> | |
class Interpreter | |
{ | |
public: | |
static void Run(std::string input) | |
{ | |
std::vector<char> m_data; | |
for (int i = 0; i < 30000; i++) | |
m_data.push_back(0); | |
std::stack<int> m_instructionPtrStack; //for [] | |
int m_dataPointer = 0, m_instructionPointer = 0; | |
while (m_instructionPointer < input.size()) | |
{ | |
char cur = input[m_instructionPointer]; | |
switch (cur) | |
{ | |
case '>': | |
m_dataPointer++; | |
break; | |
case '<': | |
m_dataPointer--; | |
break; | |
case '+': | |
m_data[m_dataPointer]++; | |
break; | |
case '-': | |
m_data[m_dataPointer]--; | |
break; | |
case '.': | |
std::cout << m_data[m_dataPointer]; | |
break; | |
case ',': | |
std::cout << "INPUT required: "; | |
std::cin >> m_data[m_dataPointer]; | |
break; | |
case '[': | |
m_instructionPtrStack.push(m_instructionPointer); | |
if (m_data[m_dataPointer] == 0) | |
{ | |
int m_tempInstructionPointer = m_instructionPointer; | |
while (++m_tempInstructionPointer < input.size()) | |
{ | |
char tempItem = input[m_tempInstructionPointer]; | |
if (tempItem == '[') | |
m_instructionPtrStack.push(m_tempInstructionPointer); | |
else if (tempItem == ']') | |
{ | |
int m_endInstructionPtr = m_instructionPtrStack.top(); | |
m_instructionPtrStack.pop(); | |
if (m_endInstructionPtr == m_instructionPointer) //if we popped the original instruction ptr off the stack then we have reached the matching one | |
{ | |
m_instructionPointer = m_endInstructionPtr; | |
break; | |
} | |
} | |
} | |
} | |
break; | |
case ']': | |
if (m_data[m_dataPointer] == 0) | |
m_instructionPtrStack.pop(); //if zero just continue execution | |
else | |
m_instructionPointer = m_instructionPtrStack.top(); //otherwise we keep going | |
break; | |
default: | |
break; | |
} | |
m_instructionPointer++; | |
} | |
std::cout << std::endl << "Finished executing. " << std::endl; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment