Get all subsets of a collection

后端 未结 7 571
青春惊慌失措
青春惊慌失措 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 17:15

    Here is an adaptation of the code provided by Marvin Mendes in this answer but refactored into a single method with an iterator block.

    public static IEnumerable> Subsets(IEnumerable source)
    {
        List list = source.ToList();
        int length = list.Count;
        int max = (int)Math.Pow(2, list.Count);
    
        for (int count = 0; count < max; count++)
        {
            List subset = new List();
            uint rs = 0;
            while (rs < length)
            {
                if ((count & (1u << (int)rs)) > 0)
                {
                    subset.Add(list[(int)rs]);
                }
                rs++;
            }
            yield return subset;
        }
    }
    

提交回复
热议问题