-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputClassifier.java
133 lines (85 loc) · 2.75 KB
/
InputClassifier.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
121
122
123
124
125
126
127
128
129
130
131
132
133
package dfa.utils;
import java.util.*;
public class InputClassifier<I, O> {
private DFAState<I, O> root;
public InputClassifier(DFA<I, O> dfa) {
root = dfa.getRoot();
}
public O classify(List<I> input) {
DFAState<I, O> curr = root;
for (I thisChar : input) {
if (!curr.getTransitions().contains(thisChar)) {
return null;
}
curr = curr.getDestination(thisChar);
}
return curr.getOutput();
}
public InputSection<I, O> findNext(List<I> input, int startIndex) {
if (startIndex > input.size()) {
throw new IllegalArgumentException(
"Start index: " + startIndex + ", length: " + input.size());
}
int end = startIndex;
O result = null;
DFAState<I, O> current = root;
for (int i = startIndex; i < input.size(); i++) {
I thisInput = input.get(i);
if (!current.getTransitions().contains(thisInput)) {
break;
}
current = current.getDestination(thisInput);
if (current.getOutput() != null) {
end = i+1;
result = current.getOutput();
}
}
return result == null ? null : new InputSection<>(startIndex, end, result);
}
public InputSection<I, O> findFirst(List<I> input) {
for (int i = 0; i < input.size(); i++) {
InputSection<I, O> first = findNext(input, i);
if (first != null) {
return first;
}
}
return null;
}
public InputSection<I, O> findLast(List<I> input) {
Queue<InputSection<I, O>> sections = new LinkedList<>();
int currPos = 0;
while (currPos < input.size()) {
InputSection<I, O> first = findNext(input, currPos);
if (first != null && first.getLabel() != null) {
if (!sections.isEmpty()) {
sections.remove();
}
sections.add(first);
}
currPos++;
}
return sections.peek();
}
public List<InputSection<I, O>> findAll(List<I> input) {
List<InputSection<I, O>> labels = new ArrayList<>();
int currPos = 0;
int unknownSectionStartPos = 0;
while (currPos < input.size()) {
InputSection<I, O> first = findNext(input, currPos);
if (first == null || first.getLabel() == null) {
currPos++;
} else {
if (currPos - unknownSectionStartPos > 0) {
labels.add(new InputSection<>(unknownSectionStartPos, currPos, null));
}
currPos = first.end;
unknownSectionStartPos = currPos;
labels.add(first);
}
}
if (currPos - unknownSectionStartPos > 0) {
labels.add(new InputSection<>(unknownSectionStartPos, currPos, null));
}
return labels;
}
}