Created
September 7, 2013 03:38
-
-
Save Deamon5550/6472650 to your computer and use it in GitHub Desktop.
Java brainfuck interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ca.deamon.dais.brainfuck; | |
import java.util.Arrays; | |
import java.util.Scanner; | |
public class BrainFuckInterpreter { | |
byte[] dat; | |
char[] program; | |
int counter = 0; | |
int ptr = 0; | |
Scanner in; | |
public BrainFuckInterpreter(char[] program) { | |
dat = new byte[30000]; | |
Arrays.fill(dat, (byte)0); | |
this.program = program; | |
in = new Scanner(System.in); | |
} | |
public void interpret() { | |
while(counter < program.length) { | |
interpret(program[counter]); | |
counter++; | |
} | |
} | |
private void interpret(char c) { | |
if(c == '>') { | |
ptr++; | |
} | |
if(c == '<' && ptr > 0) { | |
ptr--; | |
} | |
if(c == '+') { | |
dat[ptr]++; | |
} | |
if(c == '-') { | |
dat[ptr]--; | |
} | |
if(c == '.') { | |
System.out.print((char)dat[ptr]); | |
} | |
if(c == ',') { | |
while(!in.hasNext()); | |
dat[ptr] = in.nextByte(); | |
} | |
if(c == '[') { | |
if(dat[ptr]==0) { | |
int n = 1; | |
counter++; | |
while(n > 0 && counter < program.length) { | |
if(program[counter] == '[') n++; | |
if(program[counter] == ']') n--; | |
counter++; | |
} | |
} | |
} | |
if(c == ']') { | |
if(dat[ptr]!=0) { | |
int n = 1; | |
counter--; | |
while(n > 0 && counter < program.length) { | |
if(program[counter] == '[') n--; | |
if(program[counter] == ']') n++; | |
counter--; | |
} | |
counter++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment