Created
December 20, 2015 22:06
-
-
Save Heasummn/23a105b3d35add1b0f07 to your computer and use it in GitHub Desktop.
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
/** | |
* Created by Heasummn on 12/20/2015. | |
*/ | |
public class BFRunner { | |
public static void main(String[] args) { | |
Interpreter brainFuck = new Interpreter(); | |
brainFuck.interpret("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+."); | |
} | |
} |
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
/** | |
* Created by Heasummn on 12/20/2015. | |
*/ | |
public class Interpreter { | |
private int[] Heap = new int[30000]; | |
private int location = 0; | |
private int run = 0; | |
public void interpret(String brainFuck) { | |
while(run < brainFuck.length()) { | |
eval(brainFuck.charAt(location), brainFuck.toCharArray()); | |
run++; | |
} | |
} | |
private void eval(char command, char[] input) { | |
// TODO: If the heaps's location or value are 0, and they are decremented, then they wrap around. | |
//System.out.println(command); | |
switch (command) { | |
case '+': | |
// Increment the value inside the current location | |
Heap[location] += 1; | |
break; | |
case '>': | |
// Increment the location we are in the Heap | |
location += 1; | |
break; | |
case '-': | |
// Decrement the value in the location | |
Heap[location] -= 1; | |
break; | |
case '<': | |
// Decrement the location we are in the Heap | |
location -= 1; | |
break; | |
case '[': | |
// If the current value is 0, skip over to the matching ] | |
if (Heap[location] == 0) { | |
int depth = 1; | |
while (depth > 0) { | |
char next = input[++location]; | |
if (next == '[') | |
depth++; | |
else if(next == ']') | |
depth--; | |
} | |
} | |
// Otherwise just keep on going | |
break; | |
// If we find a ], go back to the matching [ | |
case ']': | |
int depth = 1; | |
while (depth > 0) { | |
char back = input[--location]; | |
if (back == '[') | |
depth--; | |
else if (back == ']') | |
depth++; | |
} | |
location--; | |
break; | |
case '.': | |
System.out.print((char) Heap[location]); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment