BrainF*ck is an esoteric language created in 1993 by Swiss physics student Urban Müller. (Don’t blame me, I didn’t come up with the name!) It consists of 8 instructions and is fully Turing-complete. Here is a complete implementation in Algol-24:
var MEMORY_SIZE := 65535;
var ScreenBuffer := '';
procedure Interpret(Code : String);
var
Loop := 0;
Instruction := 0;
Memory := Buffer(MEMORY_SIZE, 0);
begin
procedure Find(StartChar, EndChar, Increment);
begin
Instruction := Instruction + Increment;
while Loop > 0 Or Code[Instruction] <> EndChar do
begin
if Code[Instruction] = StartChar then
Loop := Loop + 1;
else if Code[Instruction] = EndChar then
Loop := Loop - 1;
Instruction := Instruction + Increment;
end
end
while Instruction < Length(Code) do
begin
var Value := Memory.GetValue();
case Code[Instruction] of
'>' : Memory.Advance();
'<' : Memory.Rewind();
'+' : Memory.SetValue(Value + 1);
'-' : Memory.SetValue(Value - 1);
'.' : ScreenBuffer := ScreenBuffer + Char(Value);
'[' : if Value = 0 then Find('[', ']', 1);
']' : if Value <> 0 then Find(']', '[', -1);
end
Instruction := Instruction + 1;
end
end
test 'Run BF Program';
begin
var Code := '-[------->+<]>-.-[->+++++<]>++.+++++++..+++.[--->+<]>-----.' +
'---[->+++<]>.+++[->++++<]>+.++++++++++.+++[->+++<]>+.++++++++++++.-.' +
'+++++.----------.+++++.-[->+++++<]>.';
Interpret(Code);
AssertEqual('????? ??????????', ScreenBuffer);
end
Coming in 42 lines of code, it is truly tiny! Lamborghini to the first person in the comments who can fill in the value to make the unit test pass 😀
******************************************
If you run this program:
[sierpinski.b -- display Sierpinski triangle (c) 2016 Daniel B. Cristofani] ++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]
This is the output:
Pretty amazing, huh?
Leave a Reply