Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define d 256
  4.  
  5. void search(char[], char[], int);
  6.  
  7. int main() {
  8.     char txt[] = "GEEKS FOR GEEKS";
  9.     char pat[] = "GEEK";
  10.     int q = 101; // A prime number
  11.     search(pat, txt, q);
  12.     return 0;
  13. }
  14.  
  15. void search(char pat[], char txt[], int q) {
  16.     int M = strlen(pat);
  17.     int N = strlen(txt);
  18.     int i, j;
  19.     int p = 0; // hash value for pattern
  20.     int t = 0; // hash value for txt
  21.     int h = 1;
  22.  
  23.     // The value of h would be "pow(d, M-1)%q"
  24.     for (i = 0; i < M - 1; i++) {
  25.         h = (h * d) % q;
  26.  
  27.     }
  28.  
  29.     // Calculate the hash value of pattern and first
  30.     // window of text
  31.     for (i = 0; i < M; i++) {
  32.         p = (d * p + pat[i]) % q;
  33.         t = (d * t + txt[i]) % q;
  34.     }
  35.  
  36.     // Slide the pattern over text one by one
  37.     for (i = 0; i <= N - M; i++) {
  38.         // Check the hash values of current window of text
  39.         // and pattern. If the hash values match then only
  40.         // check for characters on by one
  41.         if (p == t) {
  42.             /* Check for characters one by one */
  43.             for (j = 0; j < M; j++) {
  44.                 if (txt[i + j] != pat[j])
  45.                     break;
  46.             }
  47.  
  48.             // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
  49.             if (j == M) {
  50.                 printf("Pattern found at index %d \n", i);
  51.             }
  52.         }
  53.  
  54.         // Calculate hash value for next window of text: Remove
  55.         // leading digit, add trailing digit
  56.         if (i < N - M) {
  57.             t = (d * (t - txt[i] * h) + txt[i + M]) % q;
  58.             // We might get negative value of t, converting it
  59.             // to positive
  60.             if (t < 0) {
  61.                 t = t + q;
  62.             }
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement