-
Notifications
You must be signed in to change notification settings - Fork 0
/
turboBM.rb
141 lines (111 loc) · 2.46 KB
/
turboBM.rb
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
134
135
136
137
138
139
140
141
require 'set'
class TurboBoyerMoore
def initialize
@text = String.new
@pattern = Array.new
@suff = Array.new
@m
@n
end
def setup(sourceText, sourcePattern)
@text = sourceText
@pattern = sourcePattern
@n = @text.length
@m = @pattern.length
suffix
gPrefix
bPrefix
end
def suffix
@suff[@m - 1] = @m
g = @m - 1
f = 0
(@m - 2).downto(0) do |i|
if (i > g and @suff[i + @m - 1 - f] < (i - g))
@suff[i] = @suff[i + @m - 1 - f]
else
if (i < g)
g = i
end
f = i
while (g >= 0 and @pattern[g] == @pattern[g + @m - 1 - f])
g -= 1
end
@suff[i] = f - g
end
end
end
def gPrefix
@good = Array.new
0.upto(@m - 1) do |i|
@good[i] = @m
end
k = 0
(@m - 1).downto(0) do |i|
if (@suff[i] == (i + 1))
k.upto(@m - 2 - i) do |j|
if @good[j] == @m
@good[j] = @m - 1 - i
end
end
end
end
0.upto(@m - 2) do |i|
@good[@m - 1 - @suff[i]] = @m - 1 - i
end
end
def bPrefix
@bad = Hash.new
@alpha = Set.new
0.upto(@n - 1) do |i|
@alpha.add(@text[i].chr)
end
@alpha.each_with_index do |a, i|
@bad[a] = @m
end
0.upto(@m - 1) do |i|
@bad[@pattern[i].chr] = @m - i - 1
end
end
def search
comparisons = 0
found = false
j = 0
u = 0
shift = @m
while j <= (@n - @m)
i = @m - 1
while (i >= 0 and (comparisons += 1) and @pattern[i] == @text[i + j])
i -= 1
if (u != 0 and i == (@m - 1 - shift))
i -= u
end
end
if (i < 0)
found = true
puts "match found at #{j}"
shift = @good[0]
u = @m - shift
else
v = @m - 1 - i
turboShift = u - v
bcShift = @bad[@text[i + j].chr] - @m + 1 + i
shift = [turboShift, bcShift, @good[i]].max
if (shift == @good[i])
u = [@m - shift, v].min
else
if (turboShift < bcShift)
shift = [shift, u + 1].max
end
u = 0
end
end
j += shift
end
if !found
puts "search string not found"
end
puts "#{comparisons} comparisons were used in this search"
return comparisons
end
end