Created
November 28, 2016 16:45
-
-
Save buyoh/564d0d11b2244ee510266fc56e35c4e1 to your computer and use it in GitHub Desktop.
brainfuckインタプリタ仮置き
This file contains hidden or 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
#include<bits/stdc++.h> | |
using namespace std; | |
template<size_t buffer_size = 1024> | |
class Brainfucker{ | |
public: | |
string code; | |
string input; | |
string output; | |
// vector<int> buffer(buffer_size); | |
char buffer[buffer_size]; | |
size_t ptr_c = 0; | |
size_t ptr_v = 0; | |
size_t ptr_i = 0; | |
int fault = 0; // 本当はenum作るべき | |
// 1: ptr_v error / 2: not found ']' / 3: not found '[' | |
Brainfucker(const string& c,const string& i):code(c),input(i){reset();} | |
Brainfucker(const string& c):code(c){reset();} | |
Brainfucker(){reset();} | |
void reset(){ | |
output.clear(); | |
ptr_v = ptr_c = ptr_i = 0; | |
fault = 0; | |
fill(buffer,buffer+buffer_size,0); | |
} | |
bool is_halt(){ | |
return ptr_c == code.size() || fault; | |
} | |
bool step(){ | |
if (is_halt()) return false; | |
switch(code[ptr_c]){ | |
case '+': | |
if (ptr_v < 0 || buffer_size <= ptr_v){ | |
fault = 1; | |
return false; | |
} | |
buffer[ptr_v]=(buffer[ptr_v]+1)&255; | |
break; | |
case '-': | |
if (ptr_v < 0 || buffer_size <= ptr_v){ | |
fault = 1; | |
return false; | |
} | |
buffer[ptr_v]=(buffer[ptr_v]-1)&255; | |
break; | |
case '>': | |
ptr_v++; | |
break; | |
case '<': | |
ptr_v--; | |
break; | |
case '[': | |
if (buffer[ptr_v]==0) | |
while (ptr_c < code.size()-1 && code[++ptr_c]!=']'); | |
if (ptr_c == code.size()){ | |
fault = 2; | |
return false; | |
} | |
break; | |
case ']': | |
if (buffer[ptr_v]!=0) | |
while (0 < ptr_c && code[--ptr_c]!='['); | |
if (ptr_c == -1){ | |
fault = 3; | |
return false; | |
} | |
break; | |
case ',': | |
if (ptr_i < input.size()) | |
buffer[ptr_v]=input[ptr_i++]; | |
else | |
buffer[ptr_v]=0; | |
break; | |
case '.': | |
output.push_back(buffer[ptr_v]); | |
break; | |
default: | |
break; | |
} | |
ptr_c++; | |
return true; | |
} | |
void run(long long count = -1){ | |
while (step() && --count); | |
} | |
}; | |
int m,n; | |
int main(){ | |
int i,j,k; | |
Brainfucker<> bf(">++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>++++[<------>-]<.>++++[<++++++>-]<.+++.------.--------."); | |
bf.run(); | |
cout << bf.output << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment