gpt4 book ai didi

javascript - 用 JavaScript 实现 Brainf*ck 循环

转载 作者:行者123 更新时间:2023-11-29 21:53:29 25 4
gpt4 key购买 nike

所以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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com