我在理解 Java 中通用哈希函数的实现时遇到了一些麻烦。哈希函数(ax + b) mod p
应该在 H_1 的基础上实现。这个实现也应该适用于字符串。
我最近在做这个:
public class UniversalHashing {
// the hash function is a linear function (h(x) = (ax + b) mod p)
// where a and b are chosen randomly
// p is a prime number
private int a;
private int b;
private int p;
public UniversalHashing(int a, int b, int p) {
this.a = a;
this.b = b;
this.p = p;
}
public int hash(String string) {
int hash = 0;
for (int i = 0; i < string.length(); i++) {
hash = (hash * a + string.charAt(i)) % p;
}
return (hash + b) % p;
}
public static void main(String[] args) {
UniversalHashing h = new UniversalHashing(5, 3, 11);
System.out.println(h.hash("hello"));
System.out.println(h.hash("world"));
System.out.println(h.hash("hello"));
System.out.println(h.hash("world"));
}
}
这个实现是正确的,还是我在为 String 实现通用散列函数的路径上完全错误。
谢谢你帮我解决这个问题