-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFA.java
More file actions
107 lines (89 loc) · 2.35 KB
/
DFA.java
File metadata and controls
107 lines (89 loc) · 2.35 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class DFA {
String input;
HashSet<String> setOfStates;
String startState;
String acceptState;
ArrayList<String[]> transition;
HashMap<String, Node> map = new HashMap<>();
DFA(HashSet<String> setOfStates, String startState, String acceptState, ArrayList<String[]> transition) {
this.setOfStates = setOfStates;
this.startState = startState;
this.acceptState = acceptState;
this.transition = transition;
// construct the DFA
for (String stateName : this.setOfStates) {
if (stateName.equals(this.acceptState)) {
Node node = new Node();
node.changeToAcceptState();
this.map.put(stateName, node);
} else {
this.map.put(stateName, new Node());
}
}
for (int trans = 0; trans < transition.size(); trans++) {
String[] t = transition.get(trans);
Node fromState = this.map.get(t[0]);
String value = t[1];
Node toState = this.map.get(t[2]);
Edge eVal = new Edge(value, toState);
fromState.addEdge(eVal);
// this is the enable "." feature
fromState.addEdge(new Edge(".", toState));
}
}
boolean run(String input) {
this.input = input;
boolean match = false;
Node curr = this.map.get(this.startState);
for (int i = 0; i < this.input.length(); i++) {
String c = String.valueOf(input.charAt(i));
curr = curr.goToNext(c);
if (curr == null) {
break;
}
}
if (curr != null && curr.isAcceptState) {
match = true;
}
return match;
}
class Node {
ArrayList<Edge> edges;
boolean isAcceptState;
// a node can go to different edges
Node() {
this.edges = new ArrayList<>();
this.isAcceptState = false;
}
Node goToNext(String c) {
for (int i = 0; i < this.edges.size(); i++) {
// go to the next state if the current char matches or the val is dot
if (this.edges.get(i).val.equals(c) || this.edges.get(i).val.equals(".")) {
return this.edges.get(i).pointsTo;
}
}
return null;
}
void addEdge(Edge e) {
this.edges.add(e);
}
void changeToAcceptState() {
this.isAcceptState = true;
}
boolean isAcceptState() {
return this.isAcceptState;
}
}
class Edge {
String val;
Node pointsTo;
// an edge has a value and points to another state
Edge(String v, Node to) {
this.val = v;
this.pointsTo = to;
}
}
}