Jacob_Thomas

Rabin Karp

Jan 28th, 2021
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. import java.util.*;
  2. class rabin_karp{
  3.     public static void main(String args[]){
  4.         int d = 256;
  5.         Scanner sc = new Scanner(System.in);
  6.         System.out.println("Enter the text");
  7.         String text = sc.nextLine();
  8.         System.out.println("Enter the pattern");
  9.         String pattern = sc.nextLine();
  10.         int tlen = text.length();
  11.         int plen = pattern.length();
  12.         int p =0;
  13.         int t = 0;
  14.         int h = 1;
  15.         int q = 101;
  16.         for(int i = 0; i < plen-1; i++){
  17.             h = (h*d)%q;
  18.         }
  19.         for(int i = 0; i < plen; i++){
  20.             p = (d*p + pattern.charAt(i))%q;
  21.             t = (d*t + text.charAt(i))%q;
  22.         }
  23.         int j;
  24.         for (int i = 0; i <= tlen ; i++)
  25.         {
  26.             if(p == t)
  27.             {
  28.                
  29.                 for (j = 0; j < plen; j++)
  30.                 {
  31.                     if (text.charAt(i+j) != pattern.charAt(j))
  32.                         break;
  33.                 }  
  34.                 if (j == plen)
  35.                     System.out.println("Pattern found at index " + i);
  36.             }
  37.      
  38.            
  39.             if ( i < tlen-plen )
  40.             {
  41.                 t = (d*(t - text.charAt(i)*h) + text.charAt(i+plen))%q;
  42.                 if (t < 0){
  43.                     t = (t + q);
  44.                 }
  45.             }
  46.         }
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment