Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.math.BigInteger;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) {
  8.         String text = "some some Text toto find to in smths";
  9.         String pattern = "to";
  10.         System.out.println(hash(pattern));
  11.         rabinCarp(text, pattern);
  12.     }
  13.  
  14.     public static int hash(String s){
  15.         return hash(s, s.length());
  16.     }
  17.  
  18.     public static int hash(String s, int l){
  19.         int res = 0;
  20.         for (int i = 0; i < l; i++) {
  21.             res = (s.charAt(i) + res * sigma)%mod;
  22.         }
  23.         return res;
  24.     }
  25.  
  26.     public static  int nextHash(int prevHash, char prevChar, char nextChar){
  27.         return (sigma *(prevHash - prevChar * h) + nextChar) % mod;
  28.     }
  29.     static int sigma = (int) Math.pow(2, 8);
  30.     static int mod = (int) Math.pow(sigma,3);
  31.     static int h = 0;
  32.     public static void rabinCarp(String text, String pattern){
  33.         h = BigInteger.valueOf(sigma).pow(pattern.length() -1).mod(BigInteger.valueOf(mod)).intValue();
  34.         int patternHash = hash(pattern);
  35.         int textHash = hash(text, pattern.length());
  36.         for (int i = 0; i <= text.length() - pattern.length()  ; i++) {
  37.                 if(patternHash == textHash){
  38.                     boolean spuriousHit = false;
  39.                     for (int j = 0; j < pattern.length(); j++) {
  40.                         if(pattern.charAt(j) != text.charAt(i + j)){
  41.                             spuriousHit = true;
  42.                             break;
  43.                         }
  44.                     }
  45.                     if(spuriousHit){
  46.                         System.out.println("SPURIOUS HIT");
  47.                     } else {
  48.                         System.out.println(i);
  49.                     }
  50.                 }
  51.                 if(i >= text.length() - pattern.length()) break;
  52.                 textHash = nextHash(textHash, text.charAt(i), text.charAt(i + pattern.length()));
  53.         }
  54.  
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement