From fece281bb36fb5144f7cb1ce5862460076326f7e Mon Sep 17 00:00:00 2001 From: Kartik Chinda <78233115+KartikChinda@users.noreply.github.com> Date: Tue, 5 Oct 2021 18:44:34 +0530 Subject: [PATCH 1/2] Created Rabin_karp_aglorithm.md A readme file for the Rabin Karp algorithm --- RabinKarpAlgorithm/rabin_karp.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 RabinKarpAlgorithm/rabin_karp.md diff --git a/RabinKarpAlgorithm/rabin_karp.md b/RabinKarpAlgorithm/rabin_karp.md new file mode 100644 index 0000000..301721a --- /dev/null +++ b/RabinKarpAlgorithm/rabin_karp.md @@ -0,0 +1,9 @@ +## Rabin Karp Algorithm + +This is the code for the Rabin Karp algorithm, which is used for pattern finding in a given string using a hash function. Unlike Naive string matching algorithm, it does not travel through every character in the initial phase rather it filters the characters that do not match and then performs the comparison + +**Time complexity of this algorithm** +- Let the length of the string be m. +- Let the length of the pattern to be found be n. + +The average and best-case running time of the Rabin-Karp algorithm is O(n+m), but its worst-case time is O(nm). From 279effcd169f36431fd0bc362776f52989746d77 Mon Sep 17 00:00:00 2001 From: Kartik Chinda <78233115+KartikChinda@users.noreply.github.com> Date: Tue, 5 Oct 2021 18:53:35 +0530 Subject: [PATCH 2/2] Rabin Karp Algorithm Added code for the Rabin Karp algorithm --- RabinKarpAlgorithm/rabin_karp.cpp | 62 +++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 RabinKarpAlgorithm/rabin_karp.cpp diff --git a/RabinKarpAlgorithm/rabin_karp.cpp b/RabinKarpAlgorithm/rabin_karp.cpp new file mode 100644 index 0000000..d6e3817 --- /dev/null +++ b/RabinKarpAlgorithm/rabin_karp.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; + +#define ch 256 + +void search(char pattern[], char text[], int q) +{ + int M = strlen(pattern); + int N = strlen(text); + int i, j; + int p = 0; + int t = 0; + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * ch) % q; + + for (i = 0; i < M; i++) + { + p = (ch * p + pattern[i]) % q; + t = (ch * t + text[i]) % q; + } + + // Here we slide the pattern over the string one by one. + for (i = 0; i <= N - M; i++) + { + + // Checking if the hash values for each of these match. If they match, only then we move forward to check the entire pattern. + if (p == t) + { + bool flag = true; + // Checking for characters one by one + for (j = 0; j < M; j++) + { + if (text[i + j] != pattern[j]) + { + flag = false; + break; + } + } + if (j == M) + cout << "Pattern found at index " << i << endl; + } + if (i < N - M) + { + t = (ch * (t - text[i] * h) + text[i + M]) % q; + + // We might get negative value of t, so we need to convert it into a positive value. + if (t < 0) + t = (t + q); + } + } +} + +int main() +{ + char text[] = "KARTIK"; + char pattern[] = "ART"; + int q = 101; + search(pattern, text, q); + return 0; +}