2017-05-12 18 views
0

這是很明顯的,我想要做的。從集合中獲取不同的無序元組:我的代碼中的缺陷在哪裏?

我的代碼:

public class Solution 
{  
    public static void Main(String[] args) 
    { 
     Tuple<int, int> t1 = Tuple.Create(1,2); 
     Tuple<int, int> t2 = Tuple.Create(1,2); 
     Tuple<int, int> t3 = Tuple.Create(2,1); 
     List<Tuple<int, int>> tups = new List<Tuple<int, int>>() { t1, t2, t3 }; 
     var dist = tups.Distinct(new TupleComparer()); 
     foreach(var t in dist) 
      Console.WriteLine("{0},{1}", t.Item1, t.Item2); 
    } 
} 


class TupleComparer : IEqualityComparer<Tuple<int, int>> 
{ 
    public bool Equals(Tuple<int,int> a, Tuple<int, int> b) 
    { 
     return a.Item1 == b.Item1 && a.Item2 == b.Item2 
      || a.Item1 == b.Item2 && a.Item2 == b.Item1 ; 
    } 

    public int GetHashCode(Tuple<int, int> t) 
    { 
     return t.Item1 + 31 * t.Item2; 
    } 
} 

預期輸出:

1,2 

(或2,1

實際輸出:

1,2 
2,1 

缺陷在哪裏?

希望輸入這一行將使我的文本代碼比率足夠高,可以提交問題。

+0

你試過括號嗎? '(a.Item1 == b.Item1 && a.Item2 == b.Item2)|| (a.Item1 == b.Item2 && a.Item2 == b.Item1)' – itsme86

回答

1

MSDN

// If Equals() returns true for a pair of objects 
// then GetHashCode() must return the same value for these objects. 

,是不是在你的執行情況。

爲元組(1,2),產生的GetHashCode 63

爲元組(2,1),這將是33

鮮明()利用的GetHashCode,不等同。

訂單在您的實施中很重要。

Equals的實施並沒有考慮到這一點,因爲訂單在那裏並不重要。

所以結果確實不同於HashCode的觀點;)

相關問題