-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlevenshtein_automata.cpp
65 lines (57 loc) · 2.43 KB
/
levenshtein_automata.cpp
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
#include "levenshtein_automata.h"
LevenshteinAutomata::LevenshteinAutomata(){
}
void LevenshteinAutomata::SetPattern(const string & pattern, unsigned int distance){
//nfa = NFA((0, 0))
NFA<unsigned int> nfa(NFAState<unsigned int>(0,0));
//for i, c in enumerate(term):
for (unsigned int i = 0; i < pattern.size(); ++i){
string c(pattern, i, 1);
// for e in range(k + 1):
for (unsigned int e = 0; e < distance + 1; ++e){
// # Correct character
// nfa.add_transition((i, e), c, (i + 1, e))
nfa.AddTransition(NFAState<unsigned int>(i,e), NFAState<unsigned int>(i + 1,e), c);
// if e < k:
if (e < distance){
// # Deletion
// nfa.add_transition((i, e), NFA.ANY, (i, e + 1))
nfa.AddTransition(NFAState<unsigned int>(i,e), NFAState<unsigned int>(i,e + 1), "ANY");
// # Insertion
// nfa.add_transition((i, e), NFA.EPSILON, (i + 1, e + 1))
nfa.AddTransition(NFAState<unsigned int>(i,e), NFAState<unsigned int>(i + 1,e + 1), "EPSILON");
// # Substitution
// nfa.add_transition((i, e), NFA.ANY, (i + 1, e + 1))
nfa.AddTransition(NFAState<unsigned int>(i,e), NFAState<unsigned int>(i + 1,e + 1), "ANY");
}
}
}
//for e in range(k + 1):
for (unsigned int e = 0; e < distance + 1; ++e){
// if e < k:
if (e < distance)
// nfa.add_transition((len(term), e), NFA.ANY, (len(term), e + 1))
nfa.AddTransition(NFAState<unsigned int>(pattern.size(),e), NFAState<unsigned int>(pattern.size(),e + 1), "ANY");
// nfa.add_final_state((len(term), e))
nfa.AddFinalState(NFAState<unsigned int>(pattern.size(),e));
}
this->myDFA = nfa.ToDFA();
this->myDFA.setDeadState(DFAState<unsigned int>(NFAState<unsigned int>(pattern.size() + 1,pattern.size() + 1)));
}
bool LevenshteinAutomata::Match(const string& testString) const{
DFAState<unsigned int> currentState = this->myDFA.GetStartState();
for (unsigned int i = 0; i < testString.size(); ++i)
currentState = this->myDFA.GetNextDFAState(currentState, string(testString, i, 1));
if (this->myDFA.IsFinal(currentState))
return true;
else
return false;
}
extern "C"{
LevenshteinAutomata* Create(){
return new LevenshteinAutomata;
}
void Destroy(LevenshteinAutomata* obj){
delete obj;
}
}