LINQ implementation of Cartesian Product with pruning

后端 未结 3 796
盖世英雄少女心
盖世英雄少女心 2021-01-22 03:23

I hope someone is able to help me with what is, at least to me, quite a tricky algorithm.

The Problem

I have a List (1 <= size <= 5, but siz

3条回答
  •  误落风尘
    2021-01-22 03:52

    You should implement your own IEqualityComparer> and then use that in Distinct().

    The choice of hash code in the IEqualityComparer depends on your actual data, but I think something like this should be adequate if your actual data resemble those in your examples:

    class UnorderedQeuenceComparer : IEqualityComparer>
    {
        public bool Equals(IEnumerable x, IEnumerable y)
        {
            return x.OrderBy(i => i).SequenceEqual(y.OrderBy(i => i));
        }
    
        public int GetHashCode(IEnumerable obj)
        {
            return obj.Sum(i => i * i);
        }
    }
    

    The important part is that GetHashCode() should be O(N), sorting would be too slow.

提交回复
热议问题