forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Brainfuck.txt
121 lines (105 loc) · 2.7 KB
/
Brainfuck.txt
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.util.*;
class BrainFuck
{
private static Scanner ob = new Scanner(System.in);
private static int ptr; // Data pointer
// Max memory limit. It is the highest number which
// can be represented by an unsigned 16-bit binary
// number. Many computer programming environments
// beside brainfuck may have predefined
// constant values representing 65535.
private static int length = 65535;
// Array of byte type simulating memory of max
// 65535 bits from 0 to 65534.
private static byte memory[] = new byte[length];
// Interpreter function which accepts the code
// a string parameter
private static void interpret(String s)
{
int c = 0;
// Parsing through each character of the code
for (int i = 0; i < s.length(); i++)
{
// BrainFuck is a tiny language with only
// eight instructions. In this loop we check
// and execute all those eight instructions
// > moves the pointer to the right
if (s.charAt(i) == '>')
{
if (ptr == length - 1)//If memory is full
ptr = 0;//pointer is returned to zero
else
ptr ++;
}
// < moves the pointer to the left
else if (s.charAt(i) == '<')
{
if (ptr == 0) // If the pointer reaches zero
// pointer is returned to rightmost memory
// position
ptr = length - 1;
else
ptr --;
}
// + increments the value of the memory
// cell under the pointer
else if (s.charAt(i) == '+')
memory[ptr] ++;
// - decrements the value of the memory cell
// under the pointer
else if (s.charAt(i) == '-')
memory[ptr] --;
// . outputs the character signified by the
// cell at the pointer
else if (s.charAt(i) == '.')
System.out.print((char)(memory[ptr]));
// , inputs a character and store it in the
// cell at the pointer
else if (s.charAt(i) == ',')
memory[ptr] = (byte)(ob.next().charAt(0));
// [ jumps past the matching ] if the cell
// under the pointer is 0
else if (s.charAt(i) == '[')
{
if (memory[ptr] == 0)
{
i++;
while (c > 0 || s.charAt(i) != ']')
{
if (s.charAt(i) == '[')
c++;
else if (s.charAt(i) == ']')
c--;
i ++;
}
}
}
// ] jumps back to the matching [ if the
// cell under the pointer is nonzero
else if (s.charAt(i) == ']')
{
if (memory[ptr] != 0)
{
i --;
while (c > 0 || s.charAt(i) != '[')
{
if (s.charAt(i) == ']')
c ++;
else if (s.charAt(i) == '[')
c --;
i --;
}
i --;
}
}
}
}
// Driver code
public static void main(String args[])
{
System.out.println("Enter the code:");
String code = ob.nextLine();
System.out.println("Output:");
interpret(code);
}
}