Execute Brain****/Java: Difference between revisions

m
Fixed syntax highlighting.
m (Formatted the information a bit more)
m (Fixed syntax highlighting.)
 
(17 intermediate revisions by 6 users not shown)
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
In this implementation of [[Brainf***]] in [[Java]], the code is read in all at once and checked for uneven brackets (unequal amounts of [ and ] commands). If that error occurs, the code will obviously not be run.
 
Under the hood, the program memory is an <tt>ArrayList</tt> of Integers which expands only"infinitely" (limited by your system's memory) to the right (still [http://en.wikipedia.org/wiki/Turing_completeness Turing complete]). So, if the pointer moves past zero to the left, the program will exit. Due to the BufferedReader input class, return characters (ASCII 10 and 13)a are"Pointer ignoredout onof inputrange" (theerror ,message command). More detailed information canwill be found in the comments scattered about the codedisplayed.
 
Due to the <tt>BufferedReader</tt> input class, return characters ([http://www.asciitable.com ASCII] 10 and 13) are ignored on input (the , command), but are not ignored on output (the . command). In order to input anything, you'll need to append a new line.
import java.io.BufferedReader;
 
import java.io.FileNotFoundException;
Loops are handled in the <tt>jumpForward</tt> and <tt>jumpBack</tt> methods. In each method, the bracket that the code pointer is on is counted as 1 (the counter is initialized to 1). The method then moves the code pointer forward or back and counts other brackets along the way. If it finds a bracket of the same type, 1 is added to the counter; if it finds a bracket of the other type, 1 is subtracted from the counter. The search continues until the counter reaches 0. For jumping forward, the code pointer must be allowed to skip the ending bracket, or else it will jump back on the next execution iteration. For jumping back, the pointer can remain at the starting bracket. So, <tt>jumpBack</tt> offsets the next code pointer increment to make sure the check for 0 happens.
import java.io.FileReader;
 
import java.io.IOException;
More detailed information about the rest of the code can be found in the comments throughout it.<br clear=all>
import java.io.InputStreamReader;
{{works with|Java|1.5+}}
import java.util.ArrayList;
<syntaxhighlight lang="java5">import java.io.BufferedReader;
import java.io.FileNotFoundException;
/**
import java.io.FileReader;
* Interprets Brainf**k source from std in or a file.
import java.io.IOException;
*
import java.io.InputStreamReader;
* @author Mike Neurohr
import java.util.ArrayList;
*/
 
public class BF{
/**
private static int pointer;//memory pointer
* Interprets Brainf**k source from std in or a file.
private static int codeIndex;//instruction number
*
private static final int INITIAL_SIZE= 1000;//initial size of memory
* @author Mike Neurohr
private static final String instChars= "[]<>,.+-";//valid code characters
*/
public class BF{
/**
private static int pointer;//memory pointer
* The main program. Holds the input loop and error-handling.
private static int codeIndex;//instruction number
*
private static final int INITIAL_SIZE= 1000;//initial size of memory
* @param args 0: Source file others: ignored
private static final String instChars= "[]<>,.+-";//valid code characters
*/
 
public static void main(String[] args){
/**
BufferedReader source;
* The main program. Holds the input loop and error-handling.
try{
*
if(args.length == 0){//if no file specified
* @param args 0: Source file others: ignored
source= new BufferedReader(new InputStreamReader(System.in));
*/
}else{
public static void main(String[] args){
source= new BufferedReader(new FileReader(args[0]));
BufferedReader source;
}
try{
char instruction;
if(args.length == 0){//if no file specified
StringBuilder code= new StringBuilder();
source= new BufferedReader(new InputStreamReader(System.in));
}else{
//counts for loop syntax errors
source= new BufferedReader(new FileReader(args[0]));
int bCnt= 0;
}
char instruction;
//read whole source in
 
for(instruction= (char)source.read(); source.ready(); instruction=
//holds the cleaned up code
(char)source.read()){
StringBuilder code= new StringBuilder();
//remove extra characters
 
if(instChars.contains(instruction + "")){
//count for loop syntax errors
//add the instruction to the clean code
int bCnt= 0;
code.append(instruction);
 
if(instruction == '[') bCnt++;
//read whole source in
if(instruction == ']') bCnt--;
for(instruction= (char)source.read(); source.ready(); instruction=
}
(char)source.read()){
}
//remove extra characters
if(bCnt != 0){//if there is a bracket with no match
if(instChars.contains(instruction + "")){
System.err.println("Error: Uneven brackets.");
//add the instruction to the clean code
return;
code.append(instruction);
}
if(instruction == '[') bCnt++;
if(instruction == ']') bCnt--;
//set up input for ,
}
BufferedReader input=
}
new BufferedReader(new InputStreamReader(System.in));
if(bCnt != 0){//if there is a bracket with no match
//set up memory
System.err.println("Error: Uneven brackets.");
ArrayList<Integer> memory= new ArrayList<Integer>(INITIAL_SIZE);
return;
memory.add(new Integer(0));
}
 
pointer= 0; //initialize pointer
//loop through the cleanedset up codeinput andfor execute,
BufferedReader input=
for(codeIndex= 0;codeIndex < code.length();codeIndex++){
new BufferedReader(new InputStreamReader(System.in));
instruction= code.charAt(codeIndex);
//set up memory
switch(instruction){
ArrayList<Integer> memory= new ArrayList<Integer>(INITIAL_SIZE);
case '+':
memory.setadd(pointer,new memory.getInteger(pointer0) + 1);
break;
pointer= 0; //initialize pointer
case '-':
//loop through the cleaned up code and execute
memory.set(pointer, memory.get(pointer) - 1);
for(codeIndex= 0;codeIndex < code.length();codeIndex++){
break;
instruction= code.charAt(codeIndex);
case '.':
switch(instruction){
System.out.print((char)memory.get(pointer).intValue());
case '+':
//no errors possible here
memory.set(pointer, memory.get(pointer) + 1);
break;
case ',': break;
case '-':
input(memory, input);
memory.set(pointer, memory.get(pointer) - 1);
//no errors possible here
break;
case '[.':
ifSystem.out.print((char)memory.get(pointer) == 0.intValue()){;
break;
//skip the code inside the loop
case ',':
jumpForward(code);
input(memory, input);
}
break;
//if the loop can continue...
case '[':
//we don't need to check other things
if(memory.get(pointer) == 0){
break;
//skip the code inside the loop
case ']':
jumpForward(code);
//go back to the corresponding [ to check
jumpBack(code);}
//if the loop can continue...
break;
//we don't need to check other things
case '>':
pointer++break;
case ']':
while(pointer + 1 > memory.size()) memory.add(0);
if(memory.get(pointer) != 0){
break;
//go back to the corresponding [ to check
case '<':
if jumpBack(pointer == 0code){;
}
System.err.println("Pointer out of range (negative).");
//if the loop should stop...
return;
//we don't need to check other things
}
pointer--break;
break;case '>':
default: pointer++;
//gets rid of NullPointerExceptions
}
while(pointer + 1 > memory.size()) memory.add(0);
}
break;
}catch(FileNotFoundException e){
case '<':
System.err.println("Error opening file.");
}catch if(IOException--pointer < e0){
//can't do it
System.err.println("Error on input.");
System.err.println("Pointer out of range (negative).");
}
return;
}
}
default:
public static void jumpBack(StringBuilder code){
//No other characters left after the cleaning
//read back with pointer
}
//count brackets until the corresponding [
}
int bracketCnt= 1;
}catch(FileNotFoundException e){
while(codeIndex >= 0 && bracketCnt != 0){
System.err.println("Error opening file: " + args[0] + ".");
codeIndex--;
}catch(IOException e){
char inst= code.charAt(codeIndex);
System.err.println("Error on input.");
if(inst == '[') bracketCnt--;
}
if(inst == ']') bracketCnt++;
}
 
//"- 1" to offset the next "codeIndex++".
public static void jumpBack(StringBuilder code){
codeIndex= codeIndex - 1;
//initial count for the bracket we're on
}
int bracketCnt= 1;
//count brackets until the corresponding [
public static void jumpForward(StringBuilder code){
while(codeIndex >= 0 && bracketCnt != 0){
//read back with code pointer
codeIndex--;
//count brackets until the corresponding ]
char inst= code.charAt(codeIndex);
int bracketCnt= 1;
while if(codeIndexinst <== code.length('[') && bracketCnt != 0){--;
if(inst == ']') bracketCnt++;
codeIndex++;
}
char inst= code.charAt(codeIndex);
//"- 1" to offset the next "codeIndex++".
if(inst == ']') bracketCnt--;
codeIndex= codeIndex - 1;
if(inst == '[') bracketCnt++;
}
 
}
public static void jumpForward(StringBuilder code){
//initial count for the bracket we're on
public static void input(ArrayList<Integer> mem, BufferedReader input)
int bracketCnt= 1;
throws IOException{
//count brackets until the corresponding ]
int val;
while(codeIndex < code.length() && bracketCnt != 0){
//read until something comes in other than return chars
codeIndex++;
for(val= input.read(); val == 10 || val == 13; val= input.read());
char inst= code.charAt(codeIndex);
mem.set(pointer, new Integer(val));
if(inst == ']') bracketCnt--;
if(inst == '[') bracketCnt++;
}
}
 
public static void input(ArrayList<Integer> mem, BufferedReader input)
throws IOException{
int val;
//read until something comes in other than return chars
for(val= input.read(); val == 10 || val == 13; val= input.read());
mem.set(pointer, new Integer(val));
}
}</syntaxhighlight>
}
9,476

edits