Skip to content

Commit

Permalink
Update rabin_karp_search.c
Browse files Browse the repository at this point in the history
  • Loading branch information
yanglbme authored May 12, 2019
1 parent bb7199d commit 25a225c
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions searching/pattern_search/rabin_karp_search.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,34 @@ void rabin_karp_search(char *str, char *pattern, int d, int q)
int hash_p = 0; /* hash value for pattern */

/* h = pow(d, len_pat - 1) % q */
for(i = 0; i < len_pat - 1; i++)
for (i = 0; i < len_pat - 1; i++)
h = d * h % q;
/* Calculating hashing of pattern and the 1st window of text */
for(i = 0; i < len_pat; i++)
for (i = 0; i < len_pat; i++)
{
hash_p = (d*hash_p + pattern[i]) % q;
hash_s = (d*hash_s + str[i]) % q;
hash_p = (d * hash_p + pattern[i]) % q;
hash_s = (d * hash_s + str[i]) % q;
}

for(i = 0; i <= len_str - len_pat; i++)
for (i = 0; i <= len_str - len_pat; i++)
{
/* Check hash value of current window of text, and pattern
If it is match, check each character to make sure pattern
is match with current window of text */
if (hash_p == hash_s)
{
int j;
for(j = 0; j < len_pat; j++)
for (j = 0; j < len_pat; j++)
{
if(pattern[j] != str[i + j])
if (pattern[j] != str[i + j])
break;
}
if(len_pat == j)
if (len_pat == j)
printf("--Pattern is found at: %d\n", i);
}
/* Calculate hash value for next window by removing the leading
element of current window text, and adding its trailing */
hash_s = (d*(hash_s -str[i]*h) + str[i + len_pat]) % q;
hash_s = (d * (hash_s - str[i] * h) + str[i + len_pat]) % q;
/* Converting hash value to positive when it is negative */
if (hash_s < 0)
hash_s = hash_s + q;
Expand All @@ -51,7 +51,7 @@ int main()
{
char str[] = "AABCAB12AFAABCABFFEGABCAB";
char pat1[] = "ABCAB";
char pat2[] = "FFF"; /* not found */
char pat2[] = "FFF"; /* not found */
char pat3[] = "CAB";

printf("String test: %s\n", str);
Expand Down

0 comments on commit 25a225c

Please sign in to comment.