Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.benjaminurquhart.bfj;
- import java.util.ArrayList;
- import javax.script.ScriptException;
- public class BFJ {
- public static void execute(String code) throws Exception{
- execute(code, 30000);
- }
- public static void execute(String code, int cellAmount) throws Exception{
- int[] buff = new int[cellAmount < 30000 ? 30000 : cellAmount];
- ArrayList<Integer> forward = new ArrayList<>(), backward = new ArrayList<>();
- int instruction = 0, data = 0, codeLen = code.length();
- for(int i = 0; i < codeLen; i++){
- if(code.charAt(i) == '[') forward.add(i);
- if(code.charAt(i) == ']') backward.add(i);
- }
- if(forward.size() != backward.size()){
- throw new ScriptException("Unmatched jump instruction at character " + (forward.size() < backward.size() ? backward.get(backward.size() - 1) : forward.get(forward.size() - 1)));
- }
- while(instruction < codeLen){
- switch(code.charAt(instruction)){
- case ',': buff[data] = System.in.read(); break;
- case '.': System.out.print((char)buff[data]); break;
- case '+': buff[data]++; break;
- case '-': buff[data]--; break;
- case '>' : data++; break;
- case '<' : data--; break;
- case '[': instruction = (buff[data] == 0 ? backward.get(forward.indexOf(instruction)) : instruction); break;
- case ']': instruction = (buff[data] != 0 ? forward.get(backward.indexOf(instruction)) : instruction); break;
- }
- instruction++;
- }
- }
- public static void main(String[] args) throws Exception{
- execute(",.+.-.");
- }
- }
Add Comment
Please, Sign In to add comment