Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int hash_fn(string s,int n,int i)
- {
- int h=0,j,k;
- for(j=0,k=n-1; j<n,k>=0; j++,k--)
- h+=s[i+j]*pow(10,k);//hash function to calculate h with ascii value of the letter and position in the window
- return h%11;
- }
- int main()
- {
- string txt,pat;
- getline(cin,txt);//to take input with blank spaces
- getline(cin,pat);
- int lenp=pat.size(),i,j,flag=0;
- int lent=txt.size();
- int hp=hash_fn(pat,lenp,0);//calculating hash value for the pattern
- for(i=0; i<=lent-lenp; i++)
- {
- int ht=hash_fn(txt,lenp,i);//calculating hash value for windows from the text
- if(ht==hp)
- {
- for(j=0; j<lenp; j++)
- {
- if(txt[i+j]!=pat[j])//if hash value matches then checking if the letters match
- break;
- }
- if(j==lenp)
- {
- cout<<"Pattern found at index:"<<i<<endl;//if all the letters match then print
- flag=1;
- }
- }
- }
- if(flag==0)
- cout<<"Pattern not found!"<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment