0

简单地说,我有一个单词字典,我将它们添加到哈希表中。

我正在使用双散列(不是传统方法),以下是产生最好的结果。

    public static int getHashKey(String word) {

        int index = 0;

        for(int i = 0; i<word.length(); i++){

            index += Math.pow(4,  i)*((int)word.charAt(i));
            index = index % size;
        }
        return index;
    }

    public static int getDoubleHashKey(String word) {

        int jump = 1;

        for(int i = 0; i<word.length(); i++){

            jump = jump * word.charAt(i);
            jump = jump % size;
        }
        return jump;

    }

这给了我 127,000 次碰撞。我还有一个 2 倍的素数哈希表大小,它无法更改。

有什么办法可以改进双散列算法?(上述两种方法中的任何一种)。

我知道这取决于我们在哈希表中存储的内容等,但是是否有任何直观的方法或一些更普遍适用的技巧,这样我就可以避免更多的冲突。

4

1 回答 1

2

我在大约 336 531 个条目的字典上运行了一个小 Scala 程序。版本 2 (118 142) 的冲突明显少于版本 1 (305 431)。请注意,版本 2 接近最佳碰撞次数,因为 118 142 + 216 555 = 334 697,因此 334 697/336 531 = 0-216555 范围内使用的值的 99.46%。在循环使用模确实可以改进您的哈希方法。

import scala.io.Source

object Hash extends App {
    val size = 216555
    def doubleHashKey1(word: String) = {
        var jump = 1;
        for (ch <- word) {
            jump = jump * ch;
            jump = jump % size;
        }
        jump
    }

    def doubleHashKey2(word: String) = {
        var jump = 1;
        for (ch <- word) jump = jump * ch;
        jump % size;
    }

    def countCollisions(words: Set[String], hashFun: String => Int) = words.size - words.map(hashFun).size
    def readDictionary(path: String) = Source.fromFile(path).getLines.toSet

    val dict = readDictionary("words.txt")
    println(countCollisions(dict,doubleHashKey1))
    println(countCollisions(dict,doubleHashKey2))
}

为了处理整数溢出,您必须使用不同的(但实现起来很简单)方法来计算模数以返回正值。另一项测试是查看碰撞是否静态分布良好。

于 2015-04-20T22:33:08.840 回答