1+ module Rabin_Karp_Problem {
2+ // Following program is a Java implementation
3+ // of Rabin Karp Algorithm given in the CLRS book
4+
5+ public class Main {
6+ // d is the number of characters in the input alphabet
7+ public final static int d = 256 ;
8+
9+ /* pat -> pattern
10+ txt -> text
11+ q -> A prime number
12+ */
13+ static void search (String pat , String txt , int q )
14+ {
15+ int M = pat .length ();
16+ int N = txt .length ();
17+ int i , j ;
18+ int p = 0 ; // hash value for pattern
19+ int t = 0 ; // hash value for txt
20+ int h = 1 ;
21+
22+ // The value of h would be "pow(d, M-1)%q"
23+ for (i = 0 ; i < M - 1 ; i ++)
24+ h = (h * d ) % q ;
25+
26+ // Calculate the hash value of pattern and first
27+ // window of text
28+ for (i = 0 ; i < M ; i ++) {
29+ p = (d * p + pat .charAt (i )) % q ;
30+ t = (d * t + txt .charAt (i )) % q ;
31+ }
32+
33+ // Slide the pattern over text one by one
34+ for (i = 0 ; i <= N - M ; i ++) {
35+
36+ // Check the hash values of current window of
37+ // text and pattern. If the hash values match
38+ // then only check for characters one by one
39+ if (p == t ) {
40+ /* Check for characters one by one */
41+ for (j = 0 ; j < M ; j ++) {
42+ if (txt .charAt (i + j ) != pat .charAt (j ))
43+ break ;
44+ }
45+
46+ // if p == t and pat[0...M-1] = txt[i, i+1,
47+ // ...i+M-1]
48+ if (j == M )
49+ System .out .println (
50+ "Pattern found at index " + i );
51+ }
52+
53+ // Calculate hash value for next window of text:
54+ // Remove leading digit, add trailing digit
55+ if (i < N - M ) {
56+ t = (d * (t - txt .charAt (i ) * h )
57+ + txt .charAt (i + M ))
58+ % q ;
59+
60+ // We might get negative value of t,
61+ // converting it to positive
62+ if (t < 0 )
63+ t = (t + q );
64+ }
65+ }
66+ }
67+
68+ /* Driver Code */
69+ public static void main (String [] args )
70+ {
71+ String txt = "GEEKS FOR GEEKS" ;
72+ String pat = "GEEK" ;
73+
74+ // A prime number
75+ int q = 101 ;
76+
77+ // Function Call
78+ search (pat , txt , q );
79+ }
80+ }
81+
82+ }
0 commit comments