Advertisement
aniket123422

autometa

Dec 5th, 2022
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | Source Code | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4. #define Total_characters 256
  5. using namespace std;
  6.  
  7. int ComputeNextState(string pattern, int curr_state, int max_state, int ch){
  8.     if(pattern[curr_state]== ch and curr_state < max_state){
  9.         return curr_state+1;
  10.     }
  11.  
  12.     for(int new_state= curr_state; new_state>0; --new_state){
  13.         if(pattern[new_state-1]==ch){
  14.             int i;
  15.             for(i=0; i<new_state-1; i++){
  16.                 if(pattern[i]!=pattern[curr_state-new_state+1+i])
  17.                 // if(pattern[new_state-2-i] != pattern[curr_state-1-i])  
  18.                     break;
  19.             }
  20.             if(i== new_state-1){
  21.                 return new_state;
  22.             }
  23.         }
  24.     }
  25.     return 0;
  26. }
  27. vector<vector<int>> ComputeTable(string pattern){
  28.     int m= pattern.size();
  29.     vector<vector<int>> ans(m+1, vector<int>(Total_characters));
  30.     for(int i=0; i<=m; i++){
  31.         for(int j=0; j<Total_characters; ++j){
  32.             ans[i][j]= ComputeNextState(pattern, i, m, j);
  33.         }
  34.     }
  35.     return ans;
  36. }
  37.  
  38. void AutomataAlgorithm(string text, string pattern){
  39.     int n= text.size();
  40.     int m= pattern.size();
  41.  
  42.     vector<vector<int>> table= ComputeTable(pattern);
  43.     int k=0;
  44.     for(int i=0; i<n; i++){
  45.         k= table[k][text[i]];
  46.         if(k==m){
  47.             cout<<"Pattern found with shift: "<<i-m+1<<endl;
  48.         }
  49.     }
  50. }
  51.  
  52. int main(){
  53.     string text, pattern;
  54.     cout<<"Enter the Text: ";
  55.     cin>>text;
  56.     cout<<"Enter the Pattern: ";
  57.     cin>>pattern;
  58.  
  59.     AutomataAlgorithm(text, pattern);
  60.  
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement