2015-11-02 74 views
0

每當我嘗試生成一個索引值時,我在一個索引處得到許多衝突。在一個指標300和第二個最高的碰撞是10。我認爲的問題是,如果單詞的長度爲1,2,3。他們通常導致較小的權力,因此產生一個較小的數字。導致它被添加到數量較少的桶中。有沒有多功能這不會發生?或者你能幫我解決這個問題嗎?多項式哈希函數java?

public int GetHashCompress(String str){ 
    int ply=0; 
    double mathIt=0; 
    int size = str.length(); 
    for(int j = 0 ; j< size ; j++){ 
     double x0 = (double) str.charAt(j); 
     double firstStep = (int) Math.pow(31, (size-j))*x0; 
     mathIt = mathIt + firstStep ;  // hash function +1 to increance the range to keep 33 to the power >1 

     } 
    //arrayOfRawHash.add(mathIt); // this is for testing it later 
    ply =(int) mathIt %numBucket;// this is where it is compressed 
    return ply; 

} 
+1

'String#hashCode()'怎麼樣?或者如果你想要更好的散列,MD5,SHA1,..? – zapl

回答

0

問題是我的壓縮函數。它與MAD方法的壓縮功能完美配合。 謝謝大家!

0

Jenkin's One-at-a-Time Hash爲較小的值提供了良好的雪崩行爲,並且非常容易編碼。

public static int oatHash(final String hashMe) { 
    return oatHash(hashMe.getBytes()); 
} 

public static int oatHash(byte[] hashMe) { 
    int hash = 0; 
    for (byte aHashMe : hashMe) { 
     hash += aHashMe; 
     hash += (hash << 10); 
     hash ^= (hash >> 6); 
    } 
    hash += (hash << 3); 
    hash ^= (hash >> 11); 
    hash += (hash << 15); 
    return hash; 
} 
+0

從技術上講,這個解決方案是線性的,而不是多項式,但是多項式解決方案意味着算法不會讀取字符串的所有字符。如果你正在尋找「非常快」和「分佈很好」而不是「多項式」,那麼這應該很好地滿足你的需求。 – phatfingers

0

你的散列函數碰撞,因爲它是可怕的。 31^i對於i = 0的大小,基本上每一步都會有基數爲31,31,31 * 31,31 * 31 * 31的根,這些並不是不同的素數來阻止碰撞或者一個好的雪崩級聯,並且它將會花費大量時間來完成電源例程。這些都是一遍又一遍的相同數字的倍數。

private static long hash(long v) { 
     long hash = v; 
     long h = hash; 

     switch ((int) hash & 3) { 
      case 3: 
       hash += h; 
       hash ^= hash << 32; 
       hash ^= h << 36; 
       hash += hash >> 22; 
       break; 
      case 2: 
       hash += h; 
       hash ^= hash << 22; 
       hash += hash >> 34; 
       break; 
      case 1: 
       hash += h; 
       hash ^= hash << 20; 
       hash += hash >> 2; 
     } 
     hash ^= hash << 6; 
     hash += hash >> 10; 
     hash ^= hash << 8; 
     hash += hash >> 34; 
     hash ^= hash << 50; 
     hash += hash >> 12; 
     return hash; 
    }