How to get all subsets of an array?

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

    static IEnumerable> GetSubsets(IList set)
    {
        var state = new BitArray(set.Count);
        do
            yield return Enumerable.Range(0, state.Count)
                                   .Select(i => state[i] ? set[i] : default(T));
        while (Increment(state));
    }
    
    static bool Increment(BitArray flags)
    {
        int x = flags.Count - 1; 
        while (x >= 0 && flags[x]) flags[x--] = false ;
        if (x >= 0) flags[x] = true;
        return x >= 0;
    }
    

    Usage:

    foreach(var strings in GetSubsets(new[] { "dog", "cat", "mouse" }))
        Console.WriteLine(string.Join(", ", strings.ToArray()));
    

提交回复
热议问题