-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabinkarp.cpp
More file actions
119 lines (114 loc) · 2.31 KB
/
rabinkarp.cpp
File metadata and controls
119 lines (114 loc) · 2.31 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
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
/*#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
class RabinKarp
{
char Pattern[100];
int m;
int d;
long int q;
public:
RabinKarp(char p[])
{
strcpy(Pattern, p);
m = strlen(Pattern);
d = 10;
q = 100000;
}
void match(char Text[])
{
int n=strlen(Text);
long int h = long(pow(d, m-1)) % q;
long int p=0, t=0;
for (int i=0; i<m; i++)
{
p = (p*d+(Pattern[i]-'a'+1)) % q;
t = (t*d+(Text[i]-'a'+1)) % q;
}
cout << "Pattern = "<<p<<endl<<endl;
for (int s=0; s<=n-m; s++)
{
cout << "T"<<s <<"="<<t<<endl;
if (p == t)
{
int flag = 1;
for (int i=0; i<m; i++)
{
if (Pattern[i] != Text[s+i])
{
flag = 0;
break;
}
}
if (flag)
cout << "Pattern matches with shift" << s << endl;
}
if (s<n-m)
t = (((t - (Text[s]-'a'+1)*h)*d)+(Text[s+m]- 'a'+1)) % q;
}
}
};
int main()
{
char p[100], t[500];
char ch;
cout << "Enter the pattern to match: ";
cin >> p;
RabinKarp rk(p);
do
{
cout << "Enter the text to match: ";
cin >> t;
rk.match(t);
cout << "Do you want search in another text (y/n) ? ";
cin >> ch;
}
while (ch == 'y' || ch == 'Y');
return 0;
}*/
#include <iostream>
#include <string.h>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define d 10
void RK(char T[], char P[], int q){
int m = strlen(P);
int n = strlen(T);
int t = 0, p= 0, h, i, j;
h = pow(d, m-1);
h = h%q;
for(i = 0; i <m; i++){
t = (d*t+T[i]) % q;
p = (d*p+P[i]) % q;
}
for(i = 0; i<= n-m; i++){
if(p==t){
for(j = 0; j <m; j++){
if(T[i+j] != P[j])
break;
}
if(j==m)
cout<<"Found at"<<i<<endl;
}
if(i < n-m){
t = (d*(t-T[i]*h) + T[i+m]) % q;
if(t < 0)
t = t+q;
}
}
}
int main()
{
char T[30], P[10];
cout <<"enter T: ";
cin >> T;
cout <<"enter P: ";
cin >> P;
cout<<" T: "<<T<<endl;
cout<<" P: "<<P<<endl;
int q = 13;
RK(T, P, q);
return 0;
}