For the uninitiated, Brainfuck is a Turing-complete language with a total of 8 commands, all of which have literal equivalents in C:
bf c ---------------------- > ++ptr; < --ptr; + ++*ptr; - --*ptr; . putchar(*ptr); , *ptr=getchar(); [ while (*ptr) { ] }
On any Linux distribution that has a package manager, you must find and install the beef package, the Brainfuck interpreter, so you can play at home.
As you can see above, Brainfuck has a one , [β¦] management structure that translates to C as:
while (*ptr) { β¦ }
Which gives you control over IF VAR = 0 THEN GOTO 10 from BASIC. The following will call getchar() until it returns 0 :
,
But what if I only want to read the new line char \n ? After some difficulty wrapping my brain around how it can be adapted to work as a simple if , I came up with the following:
, # *ptr = getchar(); /* store input */ ---------- # *ptr -= 10; /* test for \n by subtracting 10 before loop */ [ # while (*ptr) { /* if *ptr == 0, last char read was \n */ ++++++++++ # *ptr += 10; /* wasn't \n, add 10 back to val under ptr */ >, # *(++ptr) = getchar(); ---------- # *ptr -= 10; ] # }
(If anyone has a better way to do this, please let me know)
Now let's say that I want to test the output of this loop on \r in addition to \n . How can I test this, given that I have only one opportunity to exit the loop? My goal is to be able to emulate switch nested if or if/else if s.
computer-science turing-machines brainfuck
Ryan tenney
source share