Prompt Title: Simultaneous search

Created 1 year ago
Votes 0
Views 194 times
0

Prompt Detail:

Performing a simultaneous search as each character of the query is typed in a C program can be achieved using a variety of techniques. One possible approach is to use a string matching algorithm, such as the Knuth-Morris-Pratt (KMP) algorithm, to find the occurrences of the query string within the text as the user types each character of the query. Here is an example implementation:

scss
#include <stdio.h> #include <string.h> void KMP(char* text, char* pattern, int* match_count) { int n = strlen(text); int m = strlen(pattern); int lps[m]; // Calculate the longest proper prefix that is also a suffix for each prefix of pattern int i = 0, j = 1; lps[0] = 0; while (j < m) { if (pattern[i] == pattern[j]) { lps[j] = i + 1; i++; j++; } else { if (i != 0) { i = lps[i - 1]; } else { lps[j] = 0; j++; } } } // Search for occurrences of pattern in text i = 0, j = 0; while (i < n) { if (text[i] == pattern[j]) { i++; j++; if (j == m) { (*match_count)++; j = lps[j - 1]; } } else { if (j != 0) { j = lps[j - 1]; } else { i++; } } } } int main() { char text[1000]; char pattern[1000]; int match_count = 0; printf("Enter text:\n"); fgets(text, 1000, stdin); printf("Enter pattern:\n"); fgets(pattern, 1000, stdin); int n = strlen(pattern); if (pattern[n - 1] == '\n') { pattern[n - 1] = '\0'; } // Perform simultaneous search as each character of the query is typed int i; for (i = 0; i < strlen(pattern); i++) { printf("Searching for pattern \"%s\" in text... (press Ctrl+C to stop)\n", pattern); KMP(text, pattern, &match_count); printf("Match count: %d\n", match_count); pattern[i + 1] = '\0'; // Truncate pattern to the next character } return 0; }

This program uses the KMP algorithm to search for the query string within the text as the user types each character of the query. The KMP() function takes two input strings, text and pattern, and an integer pointer match_count that keeps track of the number of matches found so far. The function first calculates the longest proper prefix that is also a suffix for each prefix of the pattern string using a loop, and then searches for occurrences of the pattern string within the text string using another loop. If a match is found, the match_count is incremented and the search continues from the next character of the pattern string.

In the main() function, the program first reads the text and pattern strings from the user using fgets(). It then performs the simultaneous search as each character of the query is typed by iterating over the characters of the pattern string and calling the KMP() function with the truncated pattern string. The program prints the current pattern string being searched

avatar
Jayagovind
Shared 1 prompt
Created 1 year ago

Leave a Comment