I successfully created a BrainFuck compiler in JavaScript, which functions perfectly with this input:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Expected output: Hello World!
However, when I use the following nested loop input, my code gets stuck in an endless loop:
+[-[<<[+[--->]-[<<<]]]>>>-]>-.---.>..>.<<<<-.<+.>>>>>.>.<<.<-.
Expected output: hello world
Upon examining the code execution step by step, it seems that the values being written to the BF memory continuously decrease and more memory cells are involved in the process. Despite not finding any apparent mistake in the execution of each statement, I am unable to determine how the loop is supposed to terminate. It appears as though the program have no other option but to loop indefinitely since the values involved will never reach zero.
Surprisingly, when I run it on the tutorialspoint Online Brainfuck Compiler, the output generated is "hello world"!
Where could my error lie?
Provided below is the code snippet for reference:
class BrainfuckInterpreter {
constructor() {
this.memory = new Array(30000).fill(0); // Brainfuck memory tape
this.pointer = 0; // Memory pointer
this.inputBuffer = ''; // Input buffer for ,
this.outputBuffer = ''; // Output buffer for .
this.loopStack = []; // Stack to keep track of loop positions
}
interpret(code, input) {
this.inputBuffer = input;
this.outputBuffer = '';
this.pointer = 0;
this.loopStack = [];
for (let i = 0; i < code.length; i++) {
const command = code.charAt(i);
switch (command) {
case '>':
this.pointer++;
break;
case '<':
this.pointer--;
break;
case '+':
this.memory[this.pointer]++;
break;
case '-':
this.memory[this.pointer]--;
break;
case '.':
this.outputBuffer += String.fromCharCode(this.memory[this.pointer]);
break;
case ',':
if (this.inputBuffer.length > 0) {
this.memory[this.pointer] = this.inputBuffer.charCodeAt(0);
this.inputBuffer = this.inputBuffer.slice(1);
} else {
this.memory[this.pointer] = 0;
}
break;
case '[':
if (this.memory[this.pointer] === 0) {
let depth = 1;
while (depth > 0) {
i++;
if (code.charAt(i) === '[') depth++;
if (code.charAt(i) === ']') depth--;
}
} else {
this.loopStack.push(i);
}
break;
case ']':
if (this.memory[this.pointer] !== 0) {
i = this.loopStack[this.loopStack.length - 1];
} else {
this.loopStack.pop();
}
break;
}
}
return this.outputBuffer;
}
}
function Compile()
{
// Example usage:
let code = '+[-[<<[+[--->]-[<<<]]]>>>-]>-.---.>..>.<<<<-.<+.>>>>>.>.<<.<-.';
let input = '';
const interpreter = new BrainfuckInterpreter();
let output = interpreter.interpret(code, input);
// Display the output
document.getElementById('output_field').innerText = this.output;
console.log(output);
}