kvhadzhiev kvhadzhiev - 4 months ago 15
Brainfuck Question

Implementing Brainf*ck loops with JavaScript

So

i
is the instruction pointer and
ptr
is the data pointer.
I'm trying to get this right:


[ - 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.


var memory = new Array();
for ( var ptr = 0; ptr < 1000; ptr++ )
memory[ptr] = 0;
var ptr = 0;
var src = document.getElementById("source").value;
for ( var i = 0; i < src.length; i++ )
{
// other code
if ( src[i] == "[" )
if ( memory[ptr] == 0 )
{
for ( var j = i; j < src.length; j++ )
if ( src[j] == "]" )
{
i = j;
break;
}
continue; // so we don't enter the next if
}
if ( src[i] == "]" )
if ( memory[ptr] != 0 )
for ( var k = i; k > 0; k-- )
if ( src[k] == "[" )
{
i = k;
break;
}
}


Everything works but trying the Hello World example with loops generates wrong output, the
[
and
]
messed up somewhere.

Any suggestions on how to fix the loop?

Edit

Here are the modified
if
s with the suggested nesting handlers, it now executes the Hello World example properly.

if ( src[i] == "[" )
if ( memory[ptr] == 0 )
{
var count = 1;
for ( var j = i + 1; j < src.length; j++ )
{
if ( src[j] == "[" )
count++;
if ( src[j] == "]" )
count--;
if ( count == 0 )
{
i = j;
break;
}
}
continue;
}
if ( src[i] == "]" )
if ( memory[ptr] != 0 )
{
var count = 1;
for ( var k = i - 1; k > 0; k-- )
{
if ( src[k] == "]" )
count++;
if ( src[k] == "[" )
count--;
if ( count == 0 )
{
i = k;
break;
}
}
}

Answer

You need to properly handle nesting of [ and ]. I would do this by having a count variable. For example, when you encounter a [ and need to find the matching ], initialize count to 1 and go through the characters. When you come across a [, increment it; on a ], decrement it. When count hits zero, you have found the matching bracket.

Comments