Yes, you read it right, we're going to code a brainfuck interpreter. It's not as difficult as it sounds, although probably will be one of the most interesting exercises we've had so far. But first a small announcement:
The rise and (quick) fall of the Lebgeeks Programming Competition:
Most of you here in the Programming section have witnessed the shy attempt at setting up the Lebgeeks Programming Competition. And you also saw how it failed :'( There are plenty of reasons why it did, and it'd be useless to discuss them. However, no one will deny that the "Exercises" series had a certain success. So I say, let's stick to that for now. It would be nice this time though, if we could avoid the duplicity of exercises and all focus on one at a time.
Coding a brainfuck interpreter:
Language: C or C++
Topics: Files, pointers.
Difficulty: Medium
What is Brainfuck?
Brainfuck is a cool (and very useless) programming language. For those of you who aren't familiar with it, I invite you to check the Wikipedia page for more info. But here's the gist of it:
Brainfuck is a language made up of 8 characters:
> increment the data pointer (to point to the next cell to the right).
< decrement the data pointer (to point to the next cell to the left).
+ increment (increase by one) the byte at the data pointer.
- decrement (decrease by one) the byte at the data pointer.
. output a character, the ASCII value of which being the byte at the data pointer.
, accept one byte of input, storing its value in the byte at the data pointer.
[ if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it
forward to the command after the matching ] command.
] if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it
back to the command after the matching [ command.
By brainfuck standards, the data pointer can only get access to 30 000 bytes (think of 30 000 bytes arrays of memory). The pointer initially starts at the beginning of the array, and according to the set of instructions seen above, the user can manipulate it freely. If the pointer gets out of bounds, it goes back to the other side of the array. For instance if it is at position 0 and we decrement it (with "<"), it will go to byte 30 000.
The exercise
You are asked to write a brainfuck interpreter. Your program should take a brainfuck source code as an input and interpret it.
To check if your program is working, you could test it on the Hello World program:
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
If it seems weird or unclear, don't hesitate to ask any question.
PS: This exercise is particularly aimed at Padre who was complaining that my last exercises were too ... "beauty contest". Padre, I'm expecting to see your code here :)