forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 3
/
rabin_karp.cpp
57 lines (48 loc) · 1.44 KB
/
rabin_karp.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
#include<bits/stdc++.h>
using namespace std;
#define MAX_CHAR 256
void search(char pattern[], char text[], int modulo_prime = 101) {
int M = strlen(pattern);
int N = strlen(text);
int i, j;
int pattern_hash = 0;
int text_hash = 0;
int power_hash = 1;
for (i = 0; i < M-1; i++) {
power_hash = (power_hash*MAX_CHAR)%modulo_prime;
}
for (i = 0; i < M; i++) {
pattern_hash = (MAX_CHAR*pattern_hash + pattern[i])%modulo_prime;
text_hash = (MAX_CHAR*text_hash + text[i])%modulo_prime;
}
for (i = 0; i <= N - M; i++) {
// Check the hash values of current window of text
// and pattern.
if (pattern_hash == text_hash) {
for (j = 0; j < M; j++) {
if (text[i+j] != pattern[j]) {
break;
}
}
if (j == M) {
cout << "Pattern found at index: " << i << "\n";
}
}
// Calculate hash value for next window of text: Remove
// leading digit, add trailing digit
if (i < N-M) {
text_hash = (MAX_CHAR*(text_hash - text[i]*power_hash) + text[i+M])%modulo_prime;
if (text_hash < 0) {
text_hash = (text_hash + modulo_prime);
}
}
}
}
int main() {
char text[N];
char pattern[N];
cin.getline(text, N);
cin.getline(pattern, N);
search(pattern, text);
return 0;
}