# C++ program for Finite Automata algorithm for Pattern Searching

In this article, we will be discussing a program to execute the Finite Automata algorithm for pattern searching.

We are provided with a text[0...n-1] and a pattern[0...m-1]. We have to find all the occurrences of the pattern[] in the text[].

For this we would preprocess the text[] and build a 2-d array to represent it. After that we just have to traverse between the elements of the text[] and the different states of the automata.

## Example

Live Demo

#include<stdio.h>
#include<string.h>
#define total_chars 256
int calc_nextstate(char *pat, int M, int state, int x) {
if (state < M && x == pat[state])
return state+1;
int ns, i;
for (ns = state; ns > 0; ns--) {
if (pat[ns-1] == x) {
for (i = 0; i < ns-1; i++)
if (pat[i] != pat[state-ns+1+i])
break;
if (i == ns-1)
return ns;
}
}
return 0;
}
//builds Finite Automata
void calc_TF(char *pat, int M, int TF[][total_chars]) {
int state, x;
for (state = 0; state <= M; ++state)
for (x = 0; x < total_chars; ++x)
TF[state][x] = calc_nextstate(pat, M, state, x);
}
//prints all occurrences of pattern in text
void calc_occur(char *pat, char *txt) {
int M = strlen(pat);
int N = strlen(txt);
int TF[M+1][total_chars];
calc_TF(pat, M, TF);
int i, state=0;
for (i = 0; i < N; i++){
state = TF[state][txt[i]];
if (state == M)
printf ("\n Given pattern is found at the index%d",i-M+1);
}
}
int main() {
}
Given pattern is found at the index 11
Given pattern is found at the index 22