Skip to content

Commit 580e8fe

Browse files
committed
Added C implementation of Rabin Karp Algorithm for Pattern Searching
1 parent 1946b4f commit 580e8fe

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

String/String Matching/rabin_karp.c

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
2+
#include<stdio.h>
3+
#include<string.h>
4+
5+
// d is the number of characters in the input alphabet
6+
#define d 256
7+
8+
/* pat -> pattern
9+
txt -> text
10+
q -> A prime number
11+
*/
12+
void search(char pat[], char txt[], int q)
13+
{
14+
int M = strlen(pat);
15+
int N = strlen(txt);
16+
int i, j;
17+
int p = 0; // hash value for pattern
18+
int t = 0; // hash value for txt
19+
int h = 1;
20+
21+
// The value of h would be "pow(d, M-1)%q"
22+
for (i = 0; i < M-1; i++)
23+
h = (h*d)%q;
24+
25+
// Calculate the hash value of pattern and first
26+
// window of text
27+
for (i = 0; i < M; i++)
28+
{
29+
p = (d*p + pat[i])%q;
30+
t = (d*t + txt[i])%q;
31+
}
32+
33+
// Slide the pattern over text one by one
34+
for (i = 0; i <= N - M; i++)
35+
{
36+
37+
// Check the hash values of current window of text
38+
// and pattern. If the hash values match then only
39+
// check for characters on by one
40+
if ( p == t )
41+
{
42+
/* Check for characters one by one */
43+
for (j = 0; j < M; j++)
44+
{
45+
if (txt[i+j] != pat[j])
46+
break;
47+
}
48+
49+
// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
50+
if (j == M)
51+
printf("Pattern found at index %d \n", i);
52+
}
53+
54+
// Calculate hash value for next window of text: Remove
55+
// leading digit, add trailing digit
56+
if ( i < N-M )
57+
{
58+
t = (d*(t - txt[i]*h) + txt[i+M])%q;
59+
60+
// We might get negative value of t, converting it
61+
// to positive
62+
if (t < 0)
63+
t = (t + q);
64+
}
65+
}
66+
}
67+
68+
/* Driver program to test above function */
69+
int main()
70+
{
71+
char txt[] = "HELLO GITHUB HELLO";
72+
char pat[] = "HELLO";
73+
int q = 101; // A prime number
74+
search(pat, txt, q);
75+
return 0;
76+
}

0 commit comments

Comments
 (0)