我正在使用 c 的 djb2 哈希函数,当我通过它运行一个名称时,我得到了数十万的哈希值,我希望能够使用数组将其放入哈希表中至少在很长的范围内有几千或更小的东西。我对如何让函数给我较小的哈希值同时仍然保持哈希值的完整性感到困惑。另外,我对如何决定用于哈希表的数组的正确大小感到困惑。预先感谢您。
unsigned long hash(char* str)
{
unsigned long hash = 5381;
int c;
for (int i = 0; i < strlen(str); ++i)
{
c = (int) str[i];
hash = ((hash << 5) + hash) + c;
}
return hash;
}
最佳答案
假设您的 djb2
版本返回一个 unsigned long
(例如,调用返回变量 foo
),并取该结果的模使用表达式对 n
取模
foo%n
将把结果从0
限制到n - 1
(包括n - 1
)。这应该具有与原始哈希值类似的理想统计特性,并且应该优于整数除法获得的结果。
关于c - 哈希函数给我极大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39979114/