Rabin Karp Algorithm for CompSci369
import java.util.*;
import java.io.*;
import java.math.*;
public class RabinKarp_Jeremy {
public static final int Q = 121;
public static final int D = 2;
public static int TALLY;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String pattern = "";
String text = "";
try {
while (true) {
pattern = "";
text = "";
text = br.readLine();
if (text == null || text == "" || text.length() <= 0) { throw new Exception(); }
pattern = br.readLine();
if (pattern == null || pattern == "" || pattern.length() <= 0) { throw new Exception(); }
TALLY = 0;
int position = RabinKarp(pattern, text);
System.out.println(TALLY);
}
}
catch (Exception e) {
}
}
private static int RabinKarp(String x, String y) {
int m = x.length();
int n = y.length();
long hx = hash(x,0,m);
long hy = hash(y,0,m);
for (int j = 0; j <= n - m; ++j) {
if (hx == hy) {
boolean isEqual = true;
for (int a = 0; a < m; a++) {
TALLY += 1;
if (x.charAt(a) != y.charAt(a+j)) {
isEqual = false;
break;
}
}
if (isEqual) {
return j;
}
}
hy = rehash(y,j,m,hy);
}
return -1;
}
private static long hash(String str, int from, int m) {
int power = 0;
long sum = 0;
for (int i = from+m-1; i >= from; i--) {
int charAt = str.charAt(i) - 'a';
sum += (charAt * power(D, power))%Q;
power++;
}
return sum % Q;
}
private static long rehash(String str, int j, int m, long h) {
try {
long a = str.charAt(j) - 'a';
long b = str.charAt(j + m) - 'a';
long hotchocolate = (a * power(D,m-1)) % Q;
long sausage = (h - hotchocolate) % Q;
long bacon = (sausage * D) % Q;
long eggs = (bacon + b) % Q;
while (eggs < 0) {
eggs += Q;
}
return eggs % Q;
}
catch (Exception e) { }
return -1;
}
private static long[] CACHE = new long[1000];
static {
for (int i = 0; i < CACHE.length; i++) {
CACHE[i] = power(D, i, true);
}
}
private static long power(int base, int power, boolean b) {
int total = 1;
for (int i = 0; i < power; i++) {
total *= base;
total %= Q;
}
return total;
}
private static long power(int base, int power) {
return CACHE[power];
}
}
|
:: About Me ::
:: Features ::
|