-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathac-automata.js
97 lines (86 loc) · 1.94 KB
/
ac-automata.js
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
const MAX_LEN = 128;
class ACNode {
constructor(data) {
this.data = data;
this.children = new Array(MAX_LEN);
this.isEndingChar = false;
this.length = 0;
this.fail = null;
}
}
class ACTree {
constructor() {
this.root = new ACNode('/');
}
insert(text = '') {
let node = this.root;
for(let char of text) {
let index = char.codePointAt(0) + 1;
if(!node.children[index]) {
node.children[index] = new ACNode(char);
}
node = node.children[index];
}
node.isEndingChar = true;
node.length = text.length;
}
buildFailurePointer() {
let root = this.root;
let queue = [];
queue.push(root);
while(queue.length > 0) {
let p = queue.shift();
for(let i = 0; i < MAX_LEN; i++) {
let pc = p.children[i];
if(!pc) {continue};
if(p === root) {
pc.fail = root;
} else {
let q = p.fail;
while(q) {
let qc = q.children[pc.data.codePointAt(0) + 1];
if(qc) {
pc.fail = qc;
break;
}
q = q.fail
}
if(!q) {
pc.fail = root;
}
}
queue.push(pc);
}
}
}
match(text) {
let root = this.root;
let n = text.length;
let p = root;
for(let i = 0; i < n; i++) {
let idx = text[i].codePointAt(0) + 1;
while(!p.children[idx] && p!= root) {
p = p.fail;
}
p = p.children[idx];
if(!p) {
p = root;
}
let tmp = p;
while(tmp != root) {
if(tmp.isEndingChar) {
console.log(`Start from ${i - p.length + 1}, length: ${p.length}`);
}
tmp = tmp.fail;
}
}
}
}
let automata = new ACTree();
let patterns = ['at', 'art', 'oars', 'soar'];
for(let pattern of patterns) {
automata.insert(pattern);
}
automata.buildFailurePointer();
automata.match("soarsoars");
console.log(automata);