我目前正在进行脑力训练并遇到循环问题。
我遵循了this的一些建议,但我似乎无法让它发挥作用。
到目前为止,这是我的代码:
<html>
<body>
<font face="consolas">
<script>
var brPos = 0;
var k = 0;
var loop = [];
var printtape = "";
var out = "";
var i = 0;
var pointer = 0;
var tape = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var source = prompt("Code").split("");
while (i<source.length+1){
if (source[i] == "<"){
pointer--;
} else if (source[i] == ">"){
pointer++;
} else if (source[i] == "+"){
tape[pointer]++;
} else if (source[i] == "-"){
tape[pointer]--;
} else if (source[i] == ","){
tape[pointer] = prompt("Input").charCodeAt(0);
} else if (source[i] == "."){
out += String.fromCharCode(tape[pointer]);
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
i++;
for (j=0;j<tape.length;j++) {
if (tape[j] > 255) {
tape[j] = 0;
} else if (tape[j] < 0) {
tape[j] = 255;
}
}
console.log(tape);
console.log(loop);
}
printtape = "";
printtape += "|";
for (i=0;i<tape.length;i++) {
if (tape[i]<10) {
printtape += "00"+tape[i]+"|";
}
if (tape[i]>=10&&tape[i]<100) {
printtape += "0"+tape[i]+"|";
}
if (tape[i]>=100) {
printtape += tape[i]+"|";
}
}
printtape += "<br>";
printtape += " ";
for (i=0;i<pointer;i++) {
printtape += " ";
}
printtape += "^";
document.write(printtape);
alert(out);
</script>
</font>
</body>
</html>
这是令人讨厌的代码(我认为):
} else if (source[i] == "["){
loop.push(pointer);
if (tape[pointer] == 0){
brPos = i;
while (k >= 0) {
if (source[brPos] == "[") {
k++;
} else if (source[brPos] == "]") {
k--;
}
}
i = brPos;
brPos = 0;
loop.pop();
}
} else if (source[i] == "]"){
i=loop[loop.length-1];
}
当我运行带有brainf * ck循环的代码(在IE中)时,它不会结束while循环并最终崩溃,我不知道为什么。
P.S。我知道评论中有人会说<font>
标记是无效的HTML,我应该使用CSS,但它有效,它比CSS更快,我真的不在乎。
答案 0 :(得分:1)
我对Brainfuck解析没有任何了解,但是代码逻辑失败并且你得到无限循环,因为brPos
是循环内的常量。您进行相同的比较并一遍又一遍地进入k++
行。如果你想离开那里,brPos
必须改变。