Adrita

ds lab 8 task 4

Jul 28th, 2020
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int hash_fn(string s,int n,int i)
  4. {
  5. int h=0,j,k;
  6. for(j=0,k=n-1; j<n,k>=0; j++,k--)
  7. h+=s[i+j]*pow(10,k);//hash function to calculate h with ascii value of the letter and position in the window
  8. return h%11;
  9. }
  10. int main()
  11. {
  12. string txt,pat;
  13. getline(cin,txt);//to take input with blank spaces
  14. getline(cin,pat);
  15. int lenp=pat.size(),i,j,flag=0;
  16. int lent=txt.size();
  17. int hp=hash_fn(pat,lenp,0);//calculating hash value for the pattern
  18. for(i=0; i<=lent-lenp; i++)
  19. {
  20. int ht=hash_fn(txt,lenp,i);//calculating hash value for windows from the text
  21. if(ht==hp)
  22. {
  23. for(j=0; j<lenp; j++)
  24. {
  25. if(txt[i+j]!=pat[j])//if hash value matches then checking if the letters match
  26. break;
  27. }
  28. if(j==lenp)
  29. {
  30. cout<<"Pattern found at index:"<<i<<endl;//if all the letters match then print
  31. flag=1;
  32. }
  33. }
  34. }
  35. if(flag==0)
  36. cout<<"Pattern not found!"<<endl;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment