|
| 1 | +//Rabin Karp Implementation in CPP |
| 2 | +// Code by Jatin Dhall |
| 3 | +#include <iostream> |
| 4 | +#include <cmath> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +//Subtracting each character by 96 so that lowercase alphabets start from 1 |
| 8 | +int calculateHash(string pattern)//Function to calculate the hash value of the pattern |
| 9 | +{ |
| 10 | + int n = pattern.length(); |
| 11 | + int hash = 0; |
| 12 | + for(int i=0;i<n;i++) |
| 13 | + { |
| 14 | + hash += ((pattern[i] - 96) * pow(10,(n-i-1))); // Formula to calculate the hash value while avoiding Spurious Hits |
| 15 | + } |
| 16 | + return hash; |
| 17 | +} |
| 18 | + |
| 19 | +int check(string substring, string pattern)//Function to check whether the characters are same bw the pattern and the substring |
| 20 | +//(Substring is the string of length m, that had the same hash value as the pattern) |
| 21 | +{ |
| 22 | + for(int i=0;i<pattern.length();i++) |
| 23 | + { |
| 24 | + if(pattern.at(i) != substring.at(i)) |
| 25 | + { |
| 26 | + return 0; |
| 27 | + } |
| 28 | + } |
| 29 | + return 1; |
| 30 | +} |
| 31 | + |
| 32 | +void search(string text,string pattern)//Function that conducts the pattern matching |
| 33 | +{ |
| 34 | + int hash = calculateHash(pattern); |
| 35 | + int hash1; |
| 36 | + string substring; |
| 37 | + int n = text.length(),m = pattern.length(); |
| 38 | + for(int i=0;i<n;i++) |
| 39 | + { |
| 40 | + hash1 = 0; |
| 41 | + substring = ""; |
| 42 | + |
| 43 | + if(n - i < m){break;}//Checking if the remaining no. of characters is less thn the length of the pattern |
| 44 | + |
| 45 | + for(int j = 0; j<m;j++)//Calculating the hash value of the substring of length m from text |
| 46 | + { |
| 47 | + substring += text[i+j]; |
| 48 | + hash1 += ((text[i + j] - 96) * pow(10,(m-j-1))); |
| 49 | + } |
| 50 | + if(hash == hash1) //If the hash value of the substring is the same as that of the pattern, then check each characters |
| 51 | + { |
| 52 | + int res = check(substring,pattern); // Check |
| 53 | + if(res == 1) |
| 54 | + { |
| 55 | + cout<<"Pattern found at : "<<i+1<<"'th Position"<<endl; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +int main() |
| 62 | +{ |
| 63 | + string text,pattern; |
| 64 | + cout<<"Enter the text : "; |
| 65 | + cin>>text; |
| 66 | + cout<<"Enter the pattern : "; |
| 67 | + cin>>pattern; |
| 68 | + search(text,pattern); |
| 69 | + |
| 70 | +} |
0 commit comments