Update rabin_karp_search.c

This commit is contained in:
Libin Yang 2019-05-12 09:27:21 +08:00 committed by GitHub
parent bb7199d706
commit 25a225c434
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 10 deletions

View File

@ -13,16 +13,16 @@ 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
@ -30,17 +30,17 @@ void rabin_karp_search(char *str, char *pattern, int d, int q)
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;
@ -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);