0% found this document useful (0 votes)
9 views1 page

Python Exps

The document contains a C program implementing the Rabin-Karp algorithm for substring search. It defines the main function, initializes the pattern and text, and includes the logic for calculating hash values and checking for matches. The program outputs the index where the pattern is found within the text.

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Python Exps

The document contains a C program implementing the Rabin-Karp algorithm for substring search. It defines the main function, initializes the pattern and text, and includes the logic for calculating hash values and checking for matches. The program outputs the index where the pattern is found within the text.

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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);
}
}
}

You might also like