

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


The Rabin - Karp string searching algorithm calculates a hash value for the pattern, and for each M-character subsequence of text to be compared. If the hash values are unequal, the algorithm will calculate the hash value for next M-character sequence. If the hash values are equal, the algorithm will compare the pattern and the M-character sequence. In this way, there is only one comparison per text subsequence, and character matching is only needed when hash values match.
Consider an M-character sequence as an M-digit number in base b , where b is the number of letters in the alphabet. The text subsequence t[i .. i+M-1] is mapped to the number x (i) = t [i]* b^M-1 + t [i+1]* b^ M-2+...+ t [i+M-1] Furthermore, given x(i) we can compute x(i+1) for the next subsequence t[i+1 .. i+M] in constant time,as follows: x (i+1) = t [i+1]∗ b^ M-1+ t [i+2]* b^ M-2+...+ t [i+M]
x (i+1) = x (i)* b (Shift left one digit)
In this way, we never explicitly compute a new value. We simply adjust the existing value as we move over one character.
If M is large, then the resulting value (b^M) will be enormous. For this reason, we hash the value by taking it mod a prime number q
The mod function is particularly useful in this case due to several of its inherent properties:- [(x mod q) + (y mod q)] mod q = (x+y) mod q (x mod q) mod q = x mod q For these reasons: h (i) = (( t [i]* b^ M-1mod q ) +( t [i+1]* b^ M-2mod q ) + ... +( t [i+M-1] mod q )) mod q h (i+1) =( h (i)* b mod q (Shift left one digit)
Calculation for 14152: ts+1=(d(ts-T[s+1]h)+T[s+m+1])mod q 10(31415–3((10^4)mod13))+2 mod 13 =10(31415- 33)+2 mod 13 =**
Let's say our pattern is "cab". And let's say our text string is "aabbcaba". For the sake of clarity, we'll use 0 through 26 here to represent letters as opposed to their actual ASCII values. For simplicity we will take mod 3.
Here we have collision but it is ignored by code line 8-