-
Notifications
You must be signed in to change notification settings - Fork 8
/
boyer moore search.jl
303 lines (233 loc) · 7.09 KB
/
boyer moore search.jl
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env julia
# coding: utf-8
# In[1]:
#boyer moore is a string search algorithm
#the main objective is to skip as many loops as possible
#the skipping depends on two heuristics
#bad character and good suffix
#a more detailed tutorial can be found in jhu material
# https://www.cs.jhu.edu/~langmea/resources/lecture_notes/strings_matching_boyer_moore.pdf
# In[2]:
#naïve search iterates the letter one by one
function naive_search(pattern,rawtext)
len_pattern=length(pattern)
len_rawtext=length(rawtext)
output=[]
#this part is stupid
#as julia allows us to do
#rawtext[i:i+len_pattern-1]==pattern
for i in 1:(len_rawtext-len_pattern+1)
ignore=false
j=1
while !ignore
if rawtext[i+j-1]!=pattern[j]
ignore=true
end
j+=1
if j>len_pattern
if !ignore
push!(output,i)
end
ignore=true
end
end
end
return output
end
# In[3]:
#preprocess for bad character
#for each index
#look back and search for every distinct letter in front of the index
#find the nearest index (as opposed to the current index)
#where every distinct letter occurs
function get_hbc(pattern)
heuristics_bc=[]
for i in 1:length(pattern)
bc=Dict()
for j in i:-1:1
if !(pattern[j] in keys(bc)) && pattern[j]!=pattern[i]
bc[pattern[j]]=i-j
end
end
push!(heuristics_bc,bc)
end
return heuristics_bc
end
# In[4]:
#the concept of good suffix is very similar to lps in kmp algo
#the only difference is bm algo starts from the right side of the pattern
#u can check kmp for reference
# https//github.com/je-suis-tm/search-and-sort/blob/master/knuth%20morris%20pratt%20search.jl
function get_hgs(pattern)
#initialize
heuristics_gs=zeros(Int8,length(pattern))
#iterate
for i in length(pattern)-1:-1:1
stop=false
left=i
right=i+1
while !stop
#compute the longest proper prefix
if pattern[left:left+length(pattern[right:end])-1]==pattern[right:end]
stop=true
break
#if no match
#increment right side and keep trying
else
right+=1
end
#if right side has reached its limit
#try left side
if right>length(pattern)
left-=1
right=i+1
end
#avoid index error
if left==0
stop=true
break
end
end
#remember to revert the pointer back to the end of the pattern
heuristics_gs[i]=right-left+length(pattern)-i
end
#the last one is always one
heuristics_gs[end]=1
return heuristics_gs
end
# In[5]:
#bm algo with bad character and good suffix heuristics
function boyer_moore(pattern,rawtext)
#get heuristics
heuristics_bc=get_hbc(pattern)
heuristics_gs=get_hgs(pattern)
#initialize
i=length(pattern)
j=length(pattern)
pos=[]
#iterate
while i<=length(rawtext)
#if no match,take the maximum skip from two different heuristics
if pattern[j]!=rawtext[i]
if rawtext[i] in keys(heuristics_bc[j])
hbc=heuristics_bc[j][rawtext[i]]
hbc+=(length(pattern)-j)
else
hbc=length(pattern)
end
hgs=heuristics_gs[j]
#move the pointer to the end of the pattern before skipping
i+=max(hbc,hgs)
j=length(pattern)
#keep matching
else
i-=1
j-=1
end
#if matched,create output
if j==0
i+=1
push!(pos,i)
i+=length(pattern)
j=length(pattern)
end
end
return pos
end
# In[6]:
#for some strange reasons
#cyrillic letters dont work the same way in julia as in python
#have to convert to latin letters
cyrillic2latin=Dict([("а", "a"),
("б", "b"),
("в", "v"),
("г", "h"),
("ґ", "g"),
("д", "d"),
("е", "e"),
("є", "ye"),
("ж", "zh"),
("з", "z"),
("и", "y"),
("і", "i"),
("ї", "yi"),
("й", "y"),
("к", "k"),
("л", "l"),
("м", "m"),
("н", "n"),
("о", "o"),
("п", "p"),
("р", "r"),
("с", "s"),
("т", "t"),
("у", "u"),
("ф", "f"),
("х", "kh"),
("ц", "ts"),
("ч", "ch"),
("ш", "sh"),
("щ", "shch"),
("ь", "()"),
("ю", "yu"),
("я", "ya"),
("А", "A"),
("Б", "B"),
("В", "V"),
("Г", "H"),
("Ґ", "G"),
("Д", "D"),
("Е", "E"),
("Є", "YE"),
("Ж", "ZH"),
("З", "Z"),
("И", "Y"),
("І", "I"),
("Ї", "YI"),
("Й", "Y"),
("К", "K"),
("Л", "L"),
("М", "M"),
("Н", "N"),
("О", "O"),
("П", "P"),
("Р", "R"),
("С", "S"),
("Т", "T"),
("У", "U"),
("Ф", "F"),
("Х", "KH"),
("Ц", "TS"),
("Ч", "CH"),
("Ш", "SH"),
("Щ", "SHCH"),
("Ь", "()"),
("Ю", "YU"),
("Я", "YA")])
rawtext="Знаменитості продовжують підтримувати Україну у війні, яку веде Російська Федерація. Серед них - актори, ведучі, співаки, письменники та найбагатші люди планети.\nТретій тиждень триває повномасштабне вторгнення російських загарбників на територію України. За цей час висловили підтримку та надали фінансову допомогу українцям, зокрема, канадський бізнесмен Ілон Маск, американська акторка українського походження Міла Куніс з чоловіком-колегою Ештоном Кутчером, американська артистка Мадонна, голлівудська кінозірка Леонардо ді Капріо та інші. А британський актор Бенедикт Камбербетч запропонував власне житло для біженців з України."
pattern="Украї";
# In[7]:
#alphabet conversion
cleantext=[]
for i in rawtext
if string(i) in keys(cyrillic2latin)
push!(cleantext,cyrillic2latin[string(i)])
else
push!(cleantext,i)
end
end
#list2string
clean_pattern=join([cyrillic2latin[string(i)] for i in pattern])
clean_text=join(cleantext);
# In[8]:
println(naive_search(clean_pattern,clean_text)==boyer_moore(clean_pattern,clean_text))
# In[9]:
#0.000008 seconds (3 allocations: 144 bytes)
@time naive_search(clean_pattern,clean_text);
# In[10]:
#0.000170 seconds (483 allocations: 12.703 KiB)
#as usual,naïve search by me is always faster than improvements...
#in python bm is actually faster
@time boyer_moore(clean_pattern,clean_text);
# In[ ]:
# In[ ]: