From 099e4f6e2ac353766fdad7c5b7f18c9e46834477 Mon Sep 17 00:00:00 2001 From: Shreya Kapoor Date: Tue, 28 Apr 2020 23:59:14 +0530 Subject: [PATCH 1/2] This is a combination of 3 commits. KMP in C Squashing commits sample IP OP added 4 space indentation 4 space indentation corrected removing 71 72 73 lines --- Knuth_Morris_Pratt_Algorithm/KMP.c | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Knuth_Morris_Pratt_Algorithm/KMP.c diff --git a/Knuth_Morris_Pratt_Algorithm/KMP.c b/Knuth_Morris_Pratt_Algorithm/KMP.c new file mode 100644 index 0000000000..bff2bb0fc6 --- /dev/null +++ b/Knuth_Morris_Pratt_Algorithm/KMP.c @@ -0,0 +1,70 @@ +// Program to implement KnuthMorrisPratt Algorithm in C + +#include +#include +#include + +void KnuthMorrisPratt(const char* X, const char* Y, int m, int n) +{ + if (*X == '\0' || m < n) + printf("Pattern is not found"); + + if (*X == '\0' || m < n) + printf("Pattern is not found"); + + if (*Y == '\0' || n == 0) + printf("Pattern with shift 0"); + + int alternate[n + 1]; + + for (int i = 0; i < n + 1; i++) + alternate[i] = 0; + + for (int i = 1; i < n; i++) + { + int j = alternate[i + 1]; + while (j > 0 && Y[j] != Y[i]) + j = alternate[j]; + + if (j > 0 || Y[j] == Y[i]) + alternate[i + 1] = j + 1; + } + + for (int i = 0, j = 0; i < m; i++) + { + if (*(X + i) == *(Y + j)) + { + if (++j == n) + printf("Pattern occurs with shift %d\n", i - j + 1); + } + else if (j > 0) { + j = alternate[j]; + i--; + } + } +} + +// Program to implement KnuthMorrisPratt Algorithm in C +int main(void) +{ + char word[20]; + gets(word); + + char pattern[20]; + gets(pattern); + + int n = strlen(word); + int m = strlen(pattern); + + KnuthMorrisPratt(word, pattern, n, m); + + return 0; +} + +///Sample IP: +// BACPARKWRPARM +// PAR + +///Sample OP: +// Pattern occurs with shift 3 +// Pattern occurs with shift 9 \ No newline at end of file From 6f59ebc82a1f69b6fc51134c9c586e2cbfbed8a0 Mon Sep 17 00:00:00 2001 From: Shreya Kapoor Date: Wed, 20 May 2020 23:25:31 +0530 Subject: [PATCH 2/2] adding blank line --- Knuth_Morris_Pratt_Algorithm/KMP.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Knuth_Morris_Pratt_Algorithm/KMP.c b/Knuth_Morris_Pratt_Algorithm/KMP.c index bff2bb0fc6..b3e804867a 100644 --- a/Knuth_Morris_Pratt_Algorithm/KMP.c +++ b/Knuth_Morris_Pratt_Algorithm/KMP.c @@ -67,4 +67,4 @@ int main(void) ///Sample OP: // Pattern occurs with shift 3 -// Pattern occurs with shift 9 \ No newline at end of file +// Pattern occurs with shift 9