【问题标题】:Getting distinct unordered tuples from a collection: where is the flaw in my code?从集合中获取不同的无序元组:我的代码中的缺陷在哪里?
【发布时间】:2017-05-12 22:21:05
【问题描述】:

我想做什么是不言自明的。

我的代码:

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

缺陷在哪里?

希望,输入此行将使我的文本与代码的比率足够高以提交问题。

【问题讨论】:

  • 你试过括号吗? (a.Item1 == b.Item1 &amp;&amp; a.Item2 == b.Item2) || (a.Item1 == b.Item2 &amp;&amp; a.Item2 == b.Item1)

标签: c# .net algorithm oop


【解决方案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。

Distinct() 使用 GetHashCode,而不是 Equals。

订单在您的实施中很重要。

Equals 实现没有考虑到这一点,因为那里的顺序无关紧要。

所以结果确实与 HashCode 的观点不同 ;)

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多