How to get all subsets of an array?

前端 未结 12 2488
既然无缘
既然无缘 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:25

    Guffa's answer had the basic functionality that I was searching, however the line with

    BitArray b = new BitArray(i);
    

    did not work for me, it gave an ArgumentOutOfRangeException. Here's my slightly adjusted and working code:

    string[] array = { "A", "B", "C","D" };
    int count = 1 << array.Length; // 2^n
    
    for (int i = 0; i < count; i++)
    {
        string[] items = new string[array.Length];
        BitArray b = new BitArray(BitConverter.GetBytes(i));
        for (int bit = 0; bit < array.Length; bit++) {
            items[bit] = b[bit] ? array[bit] : "";
        }
        Console.WriteLine(String.Join("",items));
    }
    

提交回复
热议问题