2012-12-11 55 views
7

我想從一個Vector2 []中調用時重寫GetHashCode()方法。這段代碼爲我知道的對象生成非唯一散列:我將下面的類傳遞給同一個矩形,並生成不同的散列碼。如何在c中散列一個int []#

public Shape(Rectangle r) 
     { 
      edges = new Vector2[4]; 
      edges[0] = new Vector2(0, 0); 
      edges[1] = new Vector2(r.Width, 0); 
      edges[2] = new Vector2(r.Width, r.Height); 
      edges[3] = new Vector2(0, r.Height); 
      Console.Write(edges.GetHashCode() + "\n"); 
      Position = new Vector2(r.X, r.Y);     
     } 

Vector2數組只是一堆整數。我怎樣才能創建一個獨特的散列爲整數列表?

+0

這可能應該工作。你可以發佈一個完整的例子,顯示兩個相等的向量產生不同的哈希碼? –

+1

數組不提供基於數組內容的哈希碼。所以這段代碼不起作用。你必須推出你自己的,或者如果你在.NET 4上使用[IStructuralEquatable接口](http://msdn.microsoft.com/en-us/library/system.collections.istructuralequatable.aspx)。 –

+0

@SimonWhitehead:真的嗎?那麼[Vector2.GetHashCode](http://msdn.microsoft.com/zh-cn/library/microsoft.xna.framework.vector2.gethashcode%28v=xnagamestudio.10%29.aspx)會返回什麼? –

回答

4

您可以使用這樣的事情:

public static int CombineHashCodes(params int[] hashCodes) 
{ 
    if (hashCodes == null) 
    { 
     throw new ArgumentNullException("hashCodes"); 
    } 

    if (hashCodes.Length == 0) 
    { 
     throw new IndexOutOfRangeException(); 
    } 

    if (hashCodes.Length == 1) 
    { 
     return hashCodes[0]; 
    } 

    var result = hashCodes[0]; 

    for (var i = 1; i < hashCodes.Length; i++) 
    { 
     result = CombineHashCodes(result, hashCodes[i]); 
    } 

    return result; 
} 

private static int CombineHashCodes(int h1, int h2) 
{ 
    return (h1 << 5) + h1^h2; 

    // another implementation 
    //unchecked 
    //{ 
    // var hash = 17; 

    // hash = hash * 23 + h1; 
    // hash = hash * 23 + h2; 

    // return hash; 
    //} 
} 
+0

因此,它每次循環遍歷一個數組兩個整數,每個迭代總共移動五位,並且自己遞增^下一個數字。也許我不明白位移是如何工作的,但是這不會產生一個龐大而龐大的數字嗎?我應該在最後用我的哈希表大小進行修改?無論如何,我覺得這很有幫助。 –

+2

@MaxKessler號。它使用正在運行的「桶散列」(h1與h2混合),因此它永遠不會超過int的大小,並且*位移出末尾的位將被丟棄*。請記住,通常,*哈希不是(也不可以)是唯一的*;他們只能保持穩定,並且希望分散。 – 2012-12-11 02:44:17

+0

瞭解!我改變了我的代碼,以便不會將碰撞用作識別兩個對象是否相等的方法:我做了一些研究,並且覆蓋了對象上的equals方法。非常感謝你! –

相關問題