因此,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 示例会生成错误的输出,[
和 ]
在某处搞砸了。
关于如何修复循环有什么建议吗?
编辑
以下是使用建议的嵌套处理程序修改后的 if
,它现在可以正确执行 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
为零时,您就找到了匹配的括号。
关于javascript - 使用 JavaScript 实现 Brainf*ck 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761146/