Skip to content

Commit bb7199d

Browse files
committed
Add Rabin-Karp search algorithm
1 parent 4956500 commit bb7199d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
4+
/* Kabin-Karp algorithm for pattern searching
5+
d: radix-d notation. Ex. number from 0->9, d = 10
6+
q: prime number for hashing */
7+
void rabin_karp_search(char *str, char *pattern, int d, int q)
8+
{
9+
int len_str = strlen(str);
10+
int len_pat = strlen(pattern);
11+
int i, h = 1;
12+
int hash_s = 0; /* hash value for string text */
13+
int hash_p = 0; /* hash value for pattern */
14+
15+
/* h = pow(d, len_pat - 1) % q */
16+
for(i = 0; i < len_pat - 1; i++)
17+
h = d * h % q;
18+
/* Calculating hashing of pattern and the 1st window of text */
19+
for(i = 0; i < len_pat; i++)
20+
{
21+
hash_p = (d*hash_p + pattern[i]) % q;
22+
hash_s = (d*hash_s + str[i]) % q;
23+
}
24+
25+
for(i = 0; i <= len_str - len_pat; i++)
26+
{
27+
/* Check hash value of current window of text, and pattern
28+
If it is match, check each character to make sure pattern
29+
is match with current window of text */
30+
if (hash_p == hash_s)
31+
{
32+
int j;
33+
for(j = 0; j < len_pat; j++)
34+
{
35+
if(pattern[j] != str[i + j])
36+
break;
37+
}
38+
if(len_pat == j)
39+
printf("--Pattern is found at: %d\n", i);
40+
}
41+
/* Calculate hash value for next window by removing the leading
42+
element of current window text, and adding its trailing */
43+
hash_s = (d*(hash_s -str[i]*h) + str[i + len_pat]) % q;
44+
/* Converting hash value to positive when it is negative */
45+
if (hash_s < 0)
46+
hash_s = hash_s + q;
47+
}
48+
}
49+
50+
int main()
51+
{
52+
char str[] = "AABCAB12AFAABCABFFEGABCAB";
53+
char pat1[] = "ABCAB";
54+
char pat2[] = "FFF"; /* not found */
55+
char pat3[] = "CAB";
56+
57+
printf("String test: %s\n", str);
58+
printf("Test1: search pattern %s\n", pat1);
59+
rabin_karp_search(str, pat1, 256, 29);
60+
printf("Test2: search pattern %s\n", pat2);
61+
rabin_karp_search(str, pat2, 256, 29);
62+
printf("Test3: search pattern %s\n", pat3);
63+
rabin_karp_search(str, pat3, 256, 29);
64+
return 0;
65+
}

0 commit comments

Comments
 (0)