gpt4 book ai didi

c# - 从集合中获取不同的无序元组 : where is the flaw in my code?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:53:30 24 4
gpt4 key购买 nike

我想做的事情不言自明。

我的代码:

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

漏洞在哪里?

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

最佳答案

来自 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 的观点不同 ;)

关于c# - 从集合中获取不同的无序元组 : where is the flaw in my code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43947226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com