Archived
1
Fork 0

more readable code, better testcase

This commit is contained in:
Joshua Moerman 2011-10-21 18:04:17 +02:00
parent 2420a8c61a
commit b210eb3d81
2 changed files with 17 additions and 9 deletions

View file

@ -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;
}
}
}

View file

@ -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;
}