Program for Rabin-Karp Algorithm for Pattern Searching in C

CServer Side ProgrammingProgramming

In this problem, we are given two strings a text and a pattern. Our task is to create a program for Rabin-Karp algorithm for pattern search, it will find all the occurrences of pattern in text string.

Here, we have to find all the occurrences of the pattern in the text.

Let’s take an example to understand the problem,

Input

text = “xyztrwqxyzfg” pattern = “xyz”

Output

Found at index 0
Found at index 7

Here, we will discuss the solution of the problem using the Rabin-Karp algorithm. In this algorithm, we take a window of the size of the pattern in the string and slide it one by one and match it with the pattern’s hash value. And if the hash-value match then we will check if individual characters of the pattern match with the string.

For Rabin-Karp the hash-value of text and pattern are important, for the creation of pattern we will add the character’s numeric value for every

character of the string and hash will be considered by dividing it by a prime number to make the value small.

Program for Rabin-Karp Algorithm for Pattern Searching

//Program for Rabin-Karp Algorithm for Pattern Searching

Example

 Live Demo

#include <stdio.h>
#include <string.h>
#define c 256
void search(char pattern[], char text[]){
   int M = strlen(pattern);
   int N = strlen(text);
   int i, j;
   int hashP = 0;
   int hashT = 0;
   int h = 1;
   for (i = 0; i < M - 1; i++)
   h = (h * c) % 103;
   for (i = 0; i < M; i++) {
      hashP = (c * hashP + pattern[i]) % 103;
      hashT = (c * hashT + text[i]) % 103;
   }
   for (i = 0; i <= N - M; i++) {
      if (hashP == hashT) {
         for (j = 0; j < M; j++) {
            if (text[i + j] != pattern[j])
            break;
         }
         if (j == M)
         printf("Pattern found at index %d \n", i);
      }
      if (i < N - M) {
         hashT = (c * (hashT - text[i] * h) + text[i + M]) % 103;
         if (hashT < 0)
            hashT = (hashT + 103);
      }
   }
}
int main(){
   char text[] = "xyztrwqxyzfg";
   char pattern[] = "xyz";
   printf("The pattern is found in the text at the following index : \n");
   search(pattern, text);
   return 0;
}

Output

The pattern is found in the text at the following index −

Pattern found at index 0
Pattern found at index 7
raja
Published on 17-Jul-2020 12:34:30
Advertisements