Due to the fact that nobody's ever posted this before (sarcasm) I've made a brainfuck interpreter in java. The interpreter fits in a single method, and is designed to be readable, fast, and concise, so please review on those things. I have tested it to confirm that it works.
/**
* Interpret program as a brainfuck program with the given standard input
* and output.
*
* @throws IOException
* if thrown by stdin or stdout
*/
public static void brainfuck(String program, OutputStream stdout, InputStream stdin) throws IOException {
int[] commands = program.chars().filter(c -> "><+-./[]".indexOf(c) != -1).toArray();
int commandPointer = 0;
int[] memory = new int[30_000];
int memoryPointer = 0;
while (commandPointer < commands.length) {
switch (commands[commandPointer]) {
case '>':
memoryPointer++;
if (memoryPointer >= memory.length)
memoryPointer = 0;
break;
case '<':
memoryPointer--;
if (memoryPointer < 0)
memoryPointer = memory.length - 1;
break;
case '+':
memory[memoryPointer]++;
if (memory[memoryPointer] > 255)
memory[memoryPointer] = 0;
break;
case '-':
memory[memoryPointer]--;
if (memory[memoryPointer] < 0)
memory[memoryPointer] = 255;
break;
case '.':
stdout.write(memory[memoryPointer]);
break;
case ',':
memory[memoryPointer] = stdin.read();
memory[memoryPointer] %= 256;
break;
case '[':
if (memory[memoryPointer] == 0) {
int depth = 1;
while (depth > 0) {
commandPointer++;
if (commands[commandPointer] == '[')
depth++;
else if (commands[commandPointer] == ']')
depth--;
}
}
break;
case ']':
if (memory[memoryPointer] != 0) {
int depth = 1;
while (depth > 0) {
commandPointer--;
if (commands[commandPointer] == ']')
depth++;
else if (commands[commandPointer] == '[')
depth--;
}
}
break;
}
commandPointer++;
}
}