Friday, 24 November 2017

C++ Program to Implement Rabin-Karp Algorithm


Code:

#include   iostream
#include   cstdio
#include   cstring
#include   cstdlib
using namespace std;
#define d 256
/*
 * search a substring in a string 
 */
void search(char *pat, char *txt, int q)
{
    int M = strlen(pat);
    int N = strlen(txt);
    int i, j;
    int p = 0;
    int t = 0;
    int h = 1;
    for (i = 0; i < M - 1; i++)
        h = (h * d) % q;
    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++)
    {
        if (p == t)
        {
            for (j = 0; j < M; j++)
            {
                if (txt[i + j] != pat[j])
                    break;
            }
            if (j == M)
            {
                cout<<"Pattern found at index: "<
            }
        }
        if (i < N - M)
        {
            t = (d * (t - txt[i] * h) + txt[i + M]) % q;
            if (t < 0)
              t = (t + q);
        }
    }
}

/* Main */
int main()
{
    char *txt = "Sanfoundry Linux Training";
    char *pat = "nux";
    int q = 101;
    search(pat, txt, q);
    return 0;
}


Output:

Pattern found at index: 13

------------------
(program exited with code: 1)
Press return to continue


More C++ Programs:

















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...