使用 JavaScript 实现 Brainf*ck 循环

Implementing Brainf*ck loops with JavaScript

所以i是指令指针,ptr是数据指针。 我正在努力解决这个问题:

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

一切正常,但尝试带循环的 Hello World 示例会生成错误的输出,[] 在某处搞砸了。

关于如何修复循环有什么建议吗?

编辑

这里是修改后的 ifs 和建议的嵌套处理程序,它现在可以正确执行 Hello World 示例。

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

您需要正确处理 [] 的嵌套。我会通过 count 变量来做到这一点。比如遇到一个[,需要找到匹配的],就把count初始化为1,遍历字符。当你遇到 [ 时,增加它;在 ] 上,递减它。当 count 为零时,您已找到匹配的括号。