Browse Source

more readable code, better testcase

master
Joshua Moerman 11 years ago
parent
commit
b210eb3d81
  1. 19
      brainfuck/brainfuck.hpp
  2. 7
      brainfuck/main.cpp

19
brainfuck/brainfuck.hpp

@ -12,13 +12,18 @@ namespace brainfuck_details {
// recursive funtion (from http://www.xs4all.nl/~weegen/eelis/geordi/) but templated
template <typename T, typename InputIterator, typename OutputIterator>
void b(char * c, InputIterator& in, T * & p, OutputIterator out){
for(; *c&&*c!=']'; ++c) {
(*((p+=*c=='>')-=*c=='<')+=*c=='+') -=*c=='-';
if(*c=='.') *out++ = *p;
if(*c==',') *p = *in++;
if(*c=='[') {
for(++c; *p;)b(c,in,p,out);
for(int d=0; *c!=']'||d--; ++c)d+=*c=='[';
for(; *c && *c != ']'; ++c) {
switch(*c){
case '>' : ++p; break;
case '<' : --p; break;
case '+' : ++*p; break;
case '-' : --*p; break;
case '.' : *out++ = *p; break;
case ',' : *p = *in++; break;
case '[' :
for(++c; *p;) b(c, in, p, out);
for(int d = 0; *c!=']' || d--; ++c) if(*c == '[') d++;
break;
}
}
}

7
brainfuck/main.cpp

@ -4,8 +4,11 @@
#include "brainfuck.hpp"
int main() {
brainfuck<int>("+[,.]", std::istream_iterator<int>(std::cin));
brainfuck<int>(">++++++++++++++++++++++++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]");
// will print "Hello World", or something like that.
brainfuck("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");
// will print the fibonacci sequence
brainfuck(">++++++++++++++++++++++++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]");
return 0;
}