How to get all subsets of an array?

前端 未结 12 2490
既然无缘
既然无缘 2020-11-27 17:54

Given an array: [dog, cat, mouse]

what is the most elegant way to create:

[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,         


        
12条回答
  •  眼角桃花
    2020-11-27 18:20

    Here's an easy-to-follow solution along the lines of your conception:

    private static void Test()
    {
        string[] test = new string[3] { "dog", "cat", "mouse" };
    
        foreach (var x in Subsets(test))
            Console.WriteLine("[{0}]", string.Join(",", x));
    }
    
    public static IEnumerable Subsets(T[] source)
    {
        int max = 1 << source.Length;
        for (int i = 0; i < max; i++)
        {
            T[] combination = new T[source.Length];
    
            for (int j = 0; j < source.Length; j++)
            {
                int tailIndex = source.Length - j - 1;
                combination[tailIndex] =
                    ((i & (1 << j)) != 0) ? source[tailIndex] : default(T);
            }
    
            yield return combination;
        }
    }
    

提交回复
热议问题