【发布时间】:2021-03-02 16:08:38
【问题描述】:
谁能解释一下这个哈希函数是如何工作的?我花了很多时间试图弄清楚它,但仍然不知道它是如何工作的。
完整代码来自https://gist.github.com/choaimeloo/ffb96f7e43d67e81f0d44c08837f5944#file-dictionary-c-L30
// Hashes the word (hash function posted on reddit by delipity)
// The word you want to hash is contained within new node, arrow, word.
// Hashing that will give you the index. Then you insert word into linked list.
int hash_index(char *hash_this)
{
unsigned int hash = 0;
for (int i = 0, n = strlen(hash_this); i < n; i++)
{
hash = (hash << 2) ^ hash_this[i];
}
return hash % HASHTABLE_SIZE;
}
我不明白他为什么使用 (
还有他为什么用strlen(hash_this)?
【问题讨论】:
-
哈希函数
h需要什么?if x == y then h(x) == h(y)如果你满足这一点,你就有一个有效的散列函数。理想情况下,您的函数还应该为不同的输入分配不同的哈希值。 (将所有内容散列为零是有效的,但会像废话一样执行,因为所有内容都会发生冲突)......所以该函数以确定性的方式对输入值进行攻击,这显然是有效的,位操作很便宜,为什么不呢,它是否会产生冲突取决于它获得的输入集。 -
是的,这更清楚了。现在我有兴趣将所有内容散列为零以测试该代码的时间:)
标签: c data-structures linked-list hashcode hash-function