-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFAState.java
105 lines (64 loc) · 2.19 KB
/
DFAState.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
package dfa.utils;
import java.util.*;
public class DFAState<I, O> {
private O output;
private Map<I, DFAState<I, O>> transitions = new HashMap<>();
public DFAState(O output) {
this.output = output;
}
public DFAState() {
this(null);
}
public void addTransition(I input, DFAState<I, O> next) {
transitions.put(input, next);
}
public DFAState<I, O> getDestination(I input) {
return transitions.get(input);
}
public O getOutput() {
return output;
}
public void setOutput(O output) {
if (output != null) {
this.output = output;
}
}
public Set<I> getTransitions() {
return transitions.keySet();
}
@Override public String toString() {
return "(DFA State #" + hashCode() + ")" + (output != null ? ": " + output.toString() : "");
}
private Map<DFAState<I, O>, Set<I>> getStateMap() {
Map<DFAState<I, O>, Set<I>> stateMap = new HashMap<>();
for (I input : transitions.keySet()) {
DFAState<I, O> DFAState = transitions.get(input);
Set<I> trans = stateMap.computeIfAbsent(DFAState, set -> new HashSet<>());
trans.add(input);
}
return stateMap;
}
public void print() {
System.out.println("[START] ↴");
print(" ", new HashSet<>());
System.out.println();
}
private void print(String indent, Set<DFAState<I, O>> visited) {
visited.add(this);
System.out.println(indent + toString());
Map<DFAState<I, O>, Set<I>> stateMap = getStateMap();
List<DFAState<I, O>> DFAStates = new ArrayList<>(stateMap.keySet());
for (int i = 0; i < DFAStates.size(); i++) {
String space = i < DFAStates.size() - 1 ? " | " : " ";
DFAState<I, O> DFAState = DFAStates.get(i);
System.out.println(indent + stateMap.get(DFAState).toString() + " ↴");
if (DFAState == this) {
System.out.println(indent + space + "(Self Loop)");
} else if (!visited.contains(DFAState)) {
DFAState.print(indent + space, visited);
} else {
System.out.println(indent + space + DFAState.toString() + " (Shown Above)");
}
}
}
}