From 6e1c2ec41655de54eb8a9b5a2f9a3f20237ba96b Mon Sep 17 00:00:00 2001 From: Jayanth Date: Mon, 22 Jul 2024 21:46:10 +0530 Subject: [PATCH] add more languages --- dsa/Advance/RabinKarp_README.md | 133 ++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/dsa/Advance/RabinKarp_README.md b/dsa/Advance/RabinKarp_README.md index 8fd21003f..3a84e6fe7 100644 --- a/dsa/Advance/RabinKarp_README.md +++ b/dsa/Advance/RabinKarp_README.md @@ -101,6 +101,139 @@ int main() { } ``` + +```Python showLineNumbers +def search(pat, txt, q): + d = 256 + M = len(pat) + N = len(txt) + p = 0 + t = 0 + h = 1 + + for i in range(M - 1): + h = (h * d) % q + + for i in range(M): + p = (d * p + ord(pat[i])) % q + t = (d * t + ord(txt[i])) % q + + for i in range(N - M + 1): + if p == t: + for j in range(M): + if txt[i + j] != pat[j]: + break + if j == M - 1: + print("Pattern found at index", i) + if i < N - M: + t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q + if t < 0: + t = t + q + +txt = "GEEKS FOR GEEKS" +pat = "GEEK" +q = 101 +search(pat, txt, q) + + +``` + + +``` jsx showLineNumbers +import java.util.*; + +public class RabinKarp { + public final static int d = 256; + + static void search(String pat, String txt, int q) { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + if (j == M) + System.out.println("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } + } + + public static void main(String[] args) { + String txt = "GEEKS FOR GEEKS"; + String pat = "GEEK"; + int q = 101; + search(pat, txt, q); + } +} + +``` + + + +``` jsx showLineNumbers +function search(pat, txt, q) { + const d = 256; + const M = pat.length; + const N = txt.length; + let p = 0; + let t = 0; + let h = 1; + + for (let i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (let i = 0; i < M; i++) { + p = (d * p + pat.charCodeAt(i)) % q; + t = (d * t + txt.charCodeAt(i)) % q; + } + + for (let i = 0; i <= N - M; i++) { + if (p == t) { + let j; + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + if (j == M) + console.log("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charCodeAt(i) * h) + txt.charCodeAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } +} + +const txt = "GEEKS FOR GEEKS"; +const pat = "GEEK"; +const q = 101; +search(pat, txt, q); + +``` + + + ### Complexity Analysis