-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfgTOpda.java
120 lines (90 loc) · 2.72 KB
/
cfgTOpda.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
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
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws IOException {
// Take production rules input
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of production rules: ");
int n = sc.nextInt();
Vector<Pair> rules = new Vector<>();
System.out.println("Enter production rules:");
for(int i=0; i<n; i++) {
String left = sc.next();
String right = sc.next();
rules.add(new Pair(left, right));
}
// Extract symbols
Set<String> nonTerminals = new HashSet<>();
Set<String> terminals = new HashSet<>();
for(Pair rule: rules) {
String production = rule.right;
if(production.contains("|")) {
StringTokenizer st = new StringTokenizer(production, "|");
while(st.hasMoreTokens()) {
String prod = st.nextToken();
getSymbols(prod, nonTerminals, terminals);
}
}
else {
getSymbols(production, nonTerminals, terminals);
}
if(production.equals("#")) {
terminals.add("#");
}
}
// Print PDA rules
System.out.println("PDA Production Rules:");
for(String nonTerm: nonTerminals) {
System.out.print("dl(q,null," + nonTerm + ") --> ");
boolean first = true;
for(Pair rule: rules) {
if(rule.left.equals(nonTerm)) {
String production = rule.right;
if(production.contains("|")) {
StringTokenizer st = new StringTokenizer(production, "|");
while(st.hasMoreTokens()) {
if(!first) {
System.out.print(" | ");
}
System.out.print("dl(q," + st.nextToken() + ")");
first = false;
}
}
else {
if(!first) {
System.out.print(" | ");
}
System.out.print("dl(q," + production + ")");
first = false;
}
}
}
System.out.println();
}
// Print terminal rules
for(String term: terminals) {
if(term.equals("#")) {
System.out.println("dl(q,null,null) --> dl(q,null)");
} else {
System.out.println("dl(q," + term + "," + term + ") --> dl(q,null)");
}
}
}
static void getSymbols(String production, Set<String> nonTerminals, Set<String> terminals) {
for(char ch: production.toCharArray()) {
if(Character.isUpperCase(ch)) {
nonTerminals.add(String.valueOf(ch));
} else if(Character.isLetterOrDigit(ch)) {
terminals.add(String.valueOf(ch));
}
}
}
}
class Pair {
String left;
String right;
public Pair(String left, String right) {
this.left = left;
this.right = right;
}
}