-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbrainfuck.java
More file actions
85 lines (80 loc) · 2.88 KB
/
brainfuck.java
File metadata and controls
85 lines (80 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.IOException;
import java.nio.file.*;
class brainfuck {
public static class BrainFuck {
private String code;
private int iptr;
private byte[] data;
private int dptr;
public BrainFuck(String c){
this.code = c;
this.iptr = 0;
this.data = new byte[30000];
this.dptr = 0;
}
public void run() throws IOException {
while(this.iptr < this.code.length()){
int count = 1;
switch(this.code.charAt(this.iptr)){
case '>':
this.dptr++;
break;
case '<':
this.dptr--;
break;
case '+':
this.data[this.dptr]++;
break;
case '-':
this.data[this.dptr]--;
break;
case '.':
System.out.print(Character.toString((char)this.data[this.dptr]));
break;
case ',':
this.data[this.dptr] = (byte)System.in.read();
break;
case '[':
count = 1;
if(this.data[this.dptr] == 0){
this.iptr++;
while(count > 0){
if(this.code.charAt(this.iptr) == '['){
count++;
}
else if(this.code.charAt(this.iptr) == ']'){
count--;
}
this.iptr++;
}
this.iptr--;
}
break;
case ']':
count = 1;
if(this.data[this.dptr] != 0){
this.iptr--;
while(count > 0){
if(this.code.charAt(this.iptr) == ']'){
count++;
}
else if(this.code.charAt(this.iptr) == '['){
count--;
}
this.iptr--;
}
}
break;
default:
break;
}
this.iptr++;
}
}
}
public static void main(String[] args) throws IOException {
String _c = new String(Files.readAllBytes(Paths.get(args[1])));
BrainFuck bf = new BrainFuck(_c);
bf.run();
}
}