Skip to content

Commit de76caa

Browse files
Added Rabin-Karp string matching algorithm in Others/RabinKarp.java
1 parent 36e30a0 commit de76caa

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Others/RabinKarp.java

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
3+
*/
4+
import java.util.Scanner;
5+
import java.lang.Math;
6+
7+
//An implementation of Rabin-Karp string matching algorithm
8+
//Program will simply end if there is no match
9+
public class RabinKarp {
10+
11+
public static Scanner scanner = null;
12+
public final static int d = 256;
13+
14+
public static void main(String[] args){
15+
16+
scanner = new Scanner(System.in);
17+
System.out.println("Enter String");
18+
String text = scanner.nextLine();
19+
System.out.println("Enter pattern");
20+
String pattern = scanner.nextLine();
21+
22+
int q = 101;
23+
searchPat(text,pattern,q);
24+
25+
}
26+
27+
private static void searchPat(String text, String pattern, int q) {
28+
29+
int m = pattern.length();
30+
int n = text.length();
31+
int t = 0;
32+
int p = 0;
33+
int h = 1;
34+
int j = 0;
35+
int i = 0;
36+
37+
h = (int)Math.pow(d,m-1)%q;
38+
39+
for(i =0 ; i< m; i++){
40+
//hash value is calculated for each character and then added with the hash value of the next character for pattern
41+
// as well as the text for length equal to the length of pattern
42+
p = (d*p + pattern.charAt(i))%q;
43+
t = (d*t + text.charAt(i))%q;
44+
}
45+
46+
for(i=0; i<=n-m;i++){
47+
48+
//if the calculated hash value of the pattern and text matches then
49+
//all the characters of the pattern is matched with the text of length equal to length of the pattern
50+
//if all matches then pattern exist in string
51+
//if not then the hash value of the first character of the text is subtracted and hash value of the next character after the end
52+
//of the evaluated characters is added
53+
if(p==t){
54+
55+
//if hash value matches then the individual characters are matched
56+
for(j=0;j<m;j++){
57+
58+
//if not matched then break out of the loop
59+
if(text.charAt(i+j) != pattern.charAt(j))
60+
break;
61+
}
62+
63+
//if all characters are matched then pattern exist in the string
64+
if (j==m){
65+
System.out.println("Pattern found at index " + i);
66+
}
67+
68+
}
69+
70+
//if i<n-m then hash value of the first character of the text is subtracted and hash value of the next character after the end
71+
//of the evaluated characters is added to get the hash value of the next window of characters in the text
72+
if ( i < n-m )
73+
{
74+
t = (d*(t - text.charAt(i)*h) + text.charAt(i+m))%q;
75+
76+
//if hash value becomes less than zero than q is added to make it positive
77+
if (t < 0)
78+
t = (t + q);
79+
}
80+
}
81+
82+
}
83+
84+
}

0 commit comments

Comments
 (0)