【发布时间】:2021-12-30 07:28:39
【问题描述】:
我在理解 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 实现通用哈希函数的路径上完全错误。
感谢您帮助我解决这个问题 格蕾丝
【问题讨论】:
-
顺便说一下,我们有Code Review 用于(比较)评论。
-
en.wikipedia.org/wiki/Universal_hashing#Hashing_strings 展示了一个非常相似的方法和代码。
标签: java hash computer-science universal-hashing