class rabinKarp{
public static void main(String[] args){
String txt="abcdefghijhsfdjghdsfjhgjkfdsfghk"; //test data
String ptn="fgh";
int n=txt.length();//get the lenght of the given text
int m=ptn.length();//get the lenght of the pattern given
int hashOfPatt= ptn.hashCode(); //get the hash value of the pattern
/*a loop runs shorter than the text lenght to find out the hashes tally each other*/
for(int i=0;i<n;i++){
if(i+m+1<=n){
String sub=txt.substring(i,i+m);//split the text consecutively by lenght of the pattern
int hashOfSub=sub.hashCode(); //check hash of the text and hash of the pattern match each other
if(hashOfPatt==hashOfSub){ //if the pattern and text tallies, then start character by character checking
int k=0;
boolean d=true;
/*loop runs through both the selected parts to check whether both the parts match each other*/
for(int j=i;j<i+m;j++){
if(txt.charAt(j)==ptn.charAt(k)){
k++;
}
else{
d=false;
break; //end ot loop when a un matchable part found
}
}
if(d){
System.out.println(sub); //print the pattern each and every time a match found
}
}
}
}
}
}
Thanks for sharing excellent information. Your site is so cool. I'm impressed by the details that you've on this web site. It reveals how nicely you understand this subject.
ReplyDeleteAssignment Writer
Thanks for that post. Well, I need a way to find multiple pattern matching using Rabin Karp to detect plagiarism. That is, comparing two files (like some plagiarism detection software). Can you suggest me an idea or do you have the code? Any help will be great. Thanks.
ReplyDeleteThank you for the auspicious write-up. Actually I am writing my Buy Assignment project and getting important points from different blogs and forums and This is my pleasure to being here on this blog..
ReplyDeleteI am searching about term paper writing on different blogs. I always keep coming back to read your brilliant and new blog posts.
ReplyDeleteHello, unless i'm mistaken, your not actually implementing this optimally. Rabin-Karp's only advantage is when the hashes are computed in constant time with previous hashes (eg. rolling hashes). This algorithm just flat out computes hashes for chunks of the string, which cost O(m) each.So it's not actually an O(m+n) algorithm anymore, but a O(mn) one, which is naive.
ReplyDeleteIf you give fgh at last it wont search it... just remove the +1 from if condition it will start taking it..
ReplyDelete