Showing posts with label pattern search. Show all posts
Showing posts with label pattern search. Show all posts

Mar 1, 2022

Pattern searching using finite automata

#include <iostream>
#include <cstring>
#include <string>
#define MAXSIZE 256
#define PATSIZE 10
using namespace std;

// pat = 'ABCAD' ==> 
// state | A | B | C | D |
//   0   | 1 | 0 | 0 | 0 |
//   1   | 1 | 2 | 0 | 0 |
//   2   | 1 | 0 | 3 | 0 |
//   3   | 4 | 0 | 0 | 0 |
//   4   | 1 | 0 | 0 | 5 |
//
void constructFA(char pat[], int m, int FA[][MAXSIZE])
{
    for(int i=0; i<m; i++)
    {
        FA[i][pat[0]] = 1;
        FA[i][pat[i]] = i+1;
    }
}

void findMatch(char txt[], int n, char pat[], int m, int FA[][MAXSIZE])
{
    int state=0;
    for(int i=0; i<n; i++)
    {
        state = FA[state][txt[i]];
        if(state == m)
        {
            cout << "index=" << i << ": " << string(txt).substr(i,n-i+1)<< endl;
            state = 0;
        }
    }
}
int main() {
// your code goes here
char txt[] = "This is a test. It is new.";
char pat[] = "is";
int FA[PATSIZE][MAXSIZE];
constructFA(pat, strlen(pat)-1, FA);
findMatch(txt, strlen(txt)-1, pat, strlen(pat)-1, FA);
return 0;
}

--------------------------------
  output:
index=2: is is a test. It is new.
index=5: is a test. It is new.
index=19: is new.

Apr 19, 2011

find maximum length of space in given text

void maxlenofspaces(char a[])
{
int count = 0;
int maxcount = 0;
int start = 0;
for(int i=0; a[i] != '\0'; i++)
{
if(a[i] == ' ')
{
if(!count)
start = i;
count++;
if(count > maxcount)
maxcount = count;
}
else
{
start = i-count-1;
count = 0;
}

}

cout << "\nstart index=" << start << " max spaces length=" << maxcount << endl;
}

Find Substring in a given String

int findsubstr(char* src, char* trg, int srclen, int trglen)
{
if((srclen < trglen) (srclen < 1) (trglen < 1) (!src) (!trg))
return -1;

for(int i=0; i < srclen-trglen+1; i++)
{
//now compare the src with trg
int j=0;
for(; j < trglen; j++)
{
if(src[i+j] != trg[j])
break; //not found, restart with next src character
}
if(j==trglen)
return i;
}

return -1;
}