Guest User

Untitled

a guest
Jan 22nd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. package net.benjaminurquhart.bfj;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import javax.script.ScriptException;
  6.  
  7. public class BFJ {
  8.  
  9. public static void execute(String code) throws Exception{
  10. execute(code, 30000);
  11. }
  12. public static void execute(String code, int cellAmount) throws Exception{
  13. int[] buff = new int[cellAmount < 30000 ? 30000 : cellAmount];
  14. ArrayList<Integer> forward = new ArrayList<>(), backward = new ArrayList<>();
  15. int instruction = 0, data = 0, codeLen = code.length();
  16. for(int i = 0; i < codeLen; i++){
  17. if(code.charAt(i) == '[') forward.add(i);
  18. if(code.charAt(i) == ']') backward.add(i);
  19. }
  20. if(forward.size() != backward.size()){
  21. throw new ScriptException("Unmatched jump instruction at character " + (forward.size() < backward.size() ? backward.get(backward.size() - 1) : forward.get(forward.size() - 1)));
  22. }
  23. while(instruction < codeLen){
  24. switch(code.charAt(instruction)){
  25. case ',': buff[data] = System.in.read(); break;
  26. case '.': System.out.print((char)buff[data]); break;
  27. case '+': buff[data]++; break;
  28. case '-': buff[data]--; break;
  29. case '>' : data++; break;
  30. case '<' : data--; break;
  31. case '[': instruction = (buff[data] == 0 ? backward.get(forward.indexOf(instruction)) : instruction); break;
  32. case ']': instruction = (buff[data] != 0 ? forward.get(backward.indexOf(instruction)) : instruction); break;
  33. }
  34. instruction++;
  35. }
  36. }
  37. public static void main(String[] args) throws Exception{
  38. execute(",.+.-.");
  39. }
  40. }
Add Comment
Please, Sign In to add comment