forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRabin_karp_algorithm
More file actions
74 lines (67 loc) · 1.71 KB
/
Rabin_karp_algorithm
File metadata and controls
74 lines (67 loc) · 1.71 KB
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
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
void RabinKarpAlgo(string strText, string PatternText)
{
if (strText.length() && PatternText.length())
{
int lt = strText.length();
int mt = PatternText.length();
int i, j;
int s = 0, p = 0;
const int pm = 256;
const int q = 101;
int h = 1;
bool flag = false;
for (i = 0; i < mt - 1; i++)
h = (h * pm) % q;
for (i = 0; i < mt; i++)
{
s = (pm * s + strText[i]) % q;
p = (pm * p + PatternText[i]) % q;
}
for (i = 0; i <= lt - mt; i++)
{
if (s == p)
{
for (j = 0; j < mt; j++)
if (strText[i + j] != PatternText[j])
break;
if (j == mt)
{
cout << "Pattern found at pos: " << i + 1 << endl;
flag = true;
}
}
s = (pm * (s - h * strText[i]) + strText[i + mt]) % q;
if (s < 0)
s = s + q;
}
if (!flag)
cout << "Pattern not found.." << endl;
return;
}
if ((strText.empty()) && (PatternText.empty()))
{
cout << "Text and pattern cannot be empty.." << endl;
}
else if (strText.empty())
{
cout << "Text cannot be empty.." << endl;
}
else
{
cout << "Pattern cannot be empty.." << endl;
}
return;
}
int main()
{
freopen("input.txt", "r", stdin);
string strText, PatternText;
getline(cin, strText);
getline(cin, PatternText);
RabinKarpAlgo(strText, PatternText);
return 0;
}