Advertisement
wnowak8

automat

Jan 25th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include<stdio.h>
  3. #include<string.h>
  4. using namespace std;
  5. #define NO_OF_CHARS 256  
  6.  
  7. int getNextState(string pat, int M, int state, int x)
  8. {
  9.     if (state < M&& x == pat[state]) //jesli znak jest taki sam jak nastepny to zwieksz stan
  10.         return state + 1;
  11.     int ns, i;
  12.     for (ns = state; ns > 0; ns--)
  13.     {
  14.         if (pat[ns - 1] == x)
  15.         {
  16.             for (i = 0; i < ns - 1; i++)
  17.                 if (pat[i] != pat[state - ns + 1 + i])
  18.                     break;
  19.             if (i == ns - 1)
  20.                 return ns;
  21.         }
  22.     }
  23.  
  24.     return 0;
  25. }
  26.  
  27.  
  28. void computeTF(string pat, int M, int** TF)
  29. {
  30.     int state, x;
  31.     for (state = 0; state <= M; ++state)
  32.         for (x = 0; x < NO_OF_CHARS; ++x)
  33.             TF[state][x] = getNextState(pat, M, state, x);
  34. }
  35.  
  36. void search(string pat, string txt)
  37. {
  38.     int M = pat.size();
  39.     int N = txt.size();
  40.  
  41.     int** TF = new int* [M + 1];
  42.     for (int i = 0; i < M + 1; ++i)
  43.         TF[i] = new int[NO_OF_CHARS];
  44.  
  45.     computeTF(pat, M, TF);
  46.  
  47.     int i, state = 0;
  48.     for (i = 0; i < N; i++)
  49.     {
  50.         state = TF[state][txt[i]];
  51.         if (state == M)
  52.             cout << " Pattern found at index " << i - M + 1 << endl;
  53.     }
  54. }
  55.  
  56. int main()
  57. {
  58.     string txt = "AABCABBABABABABAAABA";
  59.     string pat = "AABA";
  60.     search(pat, txt);
  61.     system("pause");
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement