Get all subsets of a collection

后端 未结 7 616
青春惊慌失措
青春惊慌失措 2021-01-13 17:05

I am trying to create a method that will return all subsets of a set.

For example if I have the collection 10,20,30 I will like to get the following ou

7条回答
  •  渐次进展
    2021-01-13 17:26

    Get all subsets of a collection of a specific subsetlength:

        public static IEnumerable> GetPermutations(IEnumerable list, int length) where T : IComparable
        {
            if (length == 1) return list.Select(t => new T[] { t });
            return GetPermutations(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) != 0)), (t1, t2) => t1.Concat(new T[] { t2 }));
        }
    
        public static IEnumerable> GetOrderedSubSets(IEnumerable list, int length) where T : IComparable
        {
            if (length == 1) return list.Select(t => new T[] { t });
            return GetOrderedSubSets(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) == -1)), (t1, t2) => t1.Concat(new T[] { t2 }));
        }
    

    Testcode:

            List set = new List { 1, 2, 3 };
            foreach (var x in GetPermutations(set, 3))
            {
                Console.WriteLine(string.Join(", ", x));
            }
            Console.WriteLine();
            foreach (var x in GetPermutations(set, 2))
            {
                Console.WriteLine(string.Join(", ", x));
            }
            Console.WriteLine();
            foreach (var x in GetOrderedSubSets(set, 2))
            {
                Console.WriteLine(string.Join(", ", x));
            }
    

    Test results:

    1, 2, 3
    1, 3, 2
    2, 1, 3
    2, 3, 1
    3, 1, 2
    3, 2, 1
    
    1, 2
    1, 3
    2, 1
    2, 3
    3, 1
    3, 2
    
    1, 2
    1, 3
    2, 3
    

提交回复
热议问题