Experiment No.
10 // Driver Code
int main() {
#include <stdio.h> char txt[] = "PROGRAMMERS
#include <string.h> PROGRAM WELL";
#define d 256 char pat[] = "PROG";
// Rabin-Karp Algorithm int q = 101;
void search(char pat[], char txt[], int q) { search(pat, txt, q);
int M = strlen(pat); // Length of pattern return 0;
int N = strlen(txt); // Length of text }
int i, j;
int p = 0; // Hash value for pattern
int t = 0; // Hash value for text window
int h = 1;
// Compute h = (d^(M-1)) % q
for (i = 0; i < M - 1; i++)
h = (h * d) % q;
// Compute initial hash values for pattern
and first window of text
for (i = 0; i < M; i++) {
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}
for (i = 0; i <= N - M; i++) {
// Check hash values
if (p == t) {
// If hash matches, check character by
character
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j])
break;
}
if (j == M)
printf("Pattern found at index %d\n",
i);
}
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) %
q;
// Ensure non-negative hash
if (t < 0)
t = (t + q);
}
}
}