HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java Brainfuck Interpreter Method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
brainfuckinterpreterjavamethod

Problem

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 -> ">':
            memoryPointer++;
            if (memoryPointer >= memory.length)
                memoryPointer = 0;
            break;
        case ' 255)
                memory[memoryPointer] = 0;
            break;
        case '-':
            memory[memoryPointer]--;
            if (memory[memoryPointer]  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++;
    }
}

Solution

You already reached two of your goals. The interpreter is very readable and very concise. It is pretty fast but could easily be made faster, but then the code would become longer and more complicated.

If you want the interpreter to stay readable, leave it as-is. Maybe document the wrap-around semantics in the Javadoc.

One thing you could change is for the , command to just be memory[memoryPointer] = stdin.read() & 0xFF;. This is more common than % 256, since this is about bit msnipulation, not about arithmetics.

Context

StackExchange Code Review Q#139015, answer score: 2

Revisions (0)

No revisions yet.