Embed presentation
Download to read offline
![Student Name: Kartik Guleria UID: 19BCS2241
Branch: BE-CSE Section/Group : CSE9/A
Semester: 5th
Subject Name: DAA LAB
Subject: CSP 309
Aim: Code and analyze to find all occurrences of a pattern P in a given string S.
Algorithms:
1. n ← length [T]
2. m ← length [P]
3. Π← COMPUTE-PREFIX-FUNCTION (P)
4. q ← 0
5. for i ← 1 to n
6. do while q > 0 and P [q + 1] ≠ T [i]
7. do q ← Π [q]
8. If P [q + 1] = T [i]
9. then q ← q + 1
10. If q = m
11. then print "Pattern occurs with shift" i - m
12. q ← Π [q]
Code:
#include <bits/stdc++.h>
using namespace std;
void search(char* pat, char* txt)
{](https://image.slidesharecdn.com/19bcs2241daa3-211122195854/75/19-bcs2241-daa_3-3-1-2048.jpg)
![int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i <= N - M; i++)
{ int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M)
cout << "Pattern found at index "
<< i << endl;
}
}
int main()
{
char txt[] = "Hello I Am Parent Class
."; char pat[] = "P";
search(pat, txt);
return 0;](https://image.slidesharecdn.com/19bcs2241daa3-211122195854/85/19-bcs2241-daa_3-3-2-320.jpg)


This document contains code and algorithms to find all occurrences of a pattern string P in a given text string S. It includes pseudocode that uses the Knuth-Morris-Pratt algorithm to compute a prefix function to match the pattern by skipping characters in the text. The code implements this algorithm to search for a pattern in a text and print the index of any matches found.
![Student Name: Kartik Guleria UID: 19BCS2241
Branch: BE-CSE Section/Group : CSE9/A
Semester: 5th
Subject Name: DAA LAB
Subject: CSP 309
Aim: Code and analyze to find all occurrences of a pattern P in a given string S.
Algorithms:
1. n ← length [T]
2. m ← length [P]
3. Π← COMPUTE-PREFIX-FUNCTION (P)
4. q ← 0
5. for i ← 1 to n
6. do while q > 0 and P [q + 1] ≠ T [i]
7. do q ← Π [q]
8. If P [q + 1] = T [i]
9. then q ← q + 1
10. If q = m
11. then print "Pattern occurs with shift" i - m
12. q ← Π [q]
Code:
#include <bits/stdc++.h>
using namespace std;
void search(char* pat, char* txt)
{](https://image.slidesharecdn.com/19bcs2241daa3-211122195854/75/19-bcs2241-daa_3-3-1-2048.jpg)
![int M = strlen(pat);
int N = strlen(txt);
for (int i = 0; i <= N - M; i++)
{ int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M)
cout << "Pattern found at index "
<< i << endl;
}
}
int main()
{
char txt[] = "Hello I Am Parent Class
."; char pat[] = "P";
search(pat, txt);
return 0;](https://image.slidesharecdn.com/19bcs2241daa3-211122195854/85/19-bcs2241-daa_3-3-2-320.jpg)

