-
Notifications
You must be signed in to change notification settings - Fork 1
/
Parser.java
84 lines (77 loc) · 1.36 KB
/
Parser.java
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
import java.util.*;
public class Parser {
static String str;
static int pos;
static Random r;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long seed = System.currentTimeMillis();
r = new Random(seed);
while (true) {
str = sc.next();
if (str.equals("!"))
break;
pos = 0;
expression();
System.out.println();
}
sc.close();
}
static void expression() {
while (pos < str.length()) {
statement();
}
}
static void statement() {
char c = str.charAt(pos);
if (Character.isAlphabetic(c))
verb();
if (c == '(')
loop();
if (c == '[')
junction();
}
static void verb() {
System.out.print(str.charAt(pos));
pos++;
}
static void loop() {
pos++;
int n = 0;
while (Character.isDigit(str.charAt(pos))) {
n *= 10;
n += str.charAt(pos) - '0';
pos++;
}
if (n != 0)
for (int i = 0; i < n; i++) {
int p = pos;
while (str.charAt(pos) != ')') {
statement();
}
if (i < n - 1)
pos = p;
}
else
while (str.charAt(pos) != ')')
pos++;
pos++;
}
static void junction() {
pos++;
if (r.nextInt(2) == 0) {
while (str.charAt(pos) != '|')
statement();
pos++;
while (str.charAt(pos) != ']')
pos++;
} else {
while (str.charAt(pos) != '|')
pos++;
pos++;
while (str.charAt(pos) != ']')
statement();
}
pos++;
}
}