I wrote this method. It's supposed to return all triplets [a, b, c] from an array of integers for which a ^ 2 + b ^ 2 = c ^ 2.
public static List<int[]> AllTripletsThatFulfilla2b2c2Equality(int[] n)
{
var combinations = from i in n
from j in n
from p in n
select new int[][] {new int[]{ i, j, p }, new int[] {p, j, i}, new int[] {i, p, j}};
return combinations.Where(x => x.Length == x.Distinct().Count() && Math.Pow(x[0], 2) + Math.Pow(x[1], 2) == Math.Pow(x[2], 2)).Distinct().ToList();
}
Distinct doesn't work.
I've tried several other ways to write this, including
public static List<int[]> AllTripletsThatFulfilla2b2c2Equality(int[] n)
{
var combinations = from i in n
from j in n
from p in n
select new[] { i, j, p };
combinations = combinations.ToList();
Func<int[], List<int[]>> combo = x =>
{
List<int[]> list = new List<int[]>();
list.Add(x);
if (!combinations.Contains(new [] { x[0], x[2], x[1] }))
{
list.Add(new[] { x[0], x[2], x[1] });
}
if (!combinations.Contains(new[] { x[2], x[1], x[0] }))
{
list.Add(new[] { x[2], x[1], x[0] });
}
list.Add(new [] { x[0], x[2], x[1] });
list.Add(new [] { x[2], x[1], x[0] });
return list;
};
return combinations.SelectMany(combo).Distinct().Where(x => x.Length == x.Distinct().Count() && Math.Pow(x[0], 2) + Math.Pow(x[1], 2) == Math.Pow(x[2], 2)).ToList();
}
and even added a comparer for Distinct:
public class TripletComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
return x[0] == y[0] && x[1] == y[1] && x[2] == y[2];
}
public int GetHashCode(int[] obj)
{
return obj.GetHashCode();
}
}
Same result when tested, this one:
Assert.Equal() Failure
Expected: List<Int32[]> [[3, 4, 5], [4, 3, 5]]
Actual: List<Int32[]> [[3, 4, 5], [3, 4, 5], [4, 3, 5], [4, 3, 5], [4, 3, 5], ...]
Somehow, it doesn't see that there are items that repeat themselves. Does anyone have any idea why, and how to fix it?