首页 > 解决方案 > 哈希函数精度问题

问题描述

我正在编写一个拼写检查单词的程序,但我的哈希函数没有为相同的单词返回相同的数字。

我的问题是我的哈希函数如何不为相同的输入返回相同的哈希值。

这是我的问题的一个最小的、可重现的示例:

// Implements a dictionary's functionality

#define HASHTABLE_SIZE 65536

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of buckets in hash table
const unsigned int N = HASHTABLE_SIZE;

// Hash table
node *table[N];
unsigned int totalWords = 0;

// Hashes word to a number
unsigned int hash(const char *word)
{
    unsigned int hash_value;

    for (int i=0, n=strlen(word); i<n; i++)
        hash_value = (hash_value << 2) ^ word[i];

    return hash_value % HASHTABLE_SIZE;
}

标签: chashtablecs50hash-function

解决方案


hash_value在散列函数中未初始化,它会造成内存破坏,从而导致不可预测的结果。从引用的帖子:

unsigned int hash = 0;


推荐阅读