LINQ implementation of Cartesian Product with pruning

后端 未结 3 767
盖世英雄少女心
盖世英雄少女心 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

    void Main()
    {
        var query =     from a in new int[] { 1 }
                        from b in new int[] { 2, 3 }
                        from c in new int[] { 2, 3 }
                        from d in new int[] { 4 }                   
                        from e in new int[] { 2, 3 }
                        select new int[] { a, b, c, d, e }; 
        query.Distinct(new ArrayComparer());
            //.Dump();
    }
     public class ArrayComparer : IEqualityComparer
        {
            public bool Equals(int[] x, int[] y)
            {            
                if (x == null || y == null)
                    return false;
    
                return x.OrderBy(i => i).SequenceEqual(y.OrderBy(i => i));
    
            }
    
            public int GetHashCode(int[] obj)
            {
                if ( obj == null || obj.Length == 0)
                    return 0;
                var hashcode = obj[0];
                for (int i = 1; i < obj.Length; i++)
                {
                    hashcode ^= obj[i];
                }
                return hashcode;
            }
        }
    

提交回复
热议问题