Search code examples
c#combinationspowerset

How to generate powersets with a maximum size in C#?


I am trying to generate all powersets from a given list within a limit of given maximum size. I've found some great answers for how to generate powersets in general and admire the solution using bitmaps found here All Possible Combinations of a list of Values or here Computing Powersets in C#.

Is there a way to generate sets with a maximum size of 'maxSize' numbers in one set? E.g. my input is {1, 2, 3, 4, 5, 6}, but I only want results with 3 or less items. Is it possible to do within the one command? I have found a solution where I iterate over all items of the result, but this is quite inefficient for large inputs with smaller maxSize.


Solution

  • It's easy with recursion:

    static public IEnumerable<List<int>> FindAllCombos(List<int> list, int maxSize, int minIndex = 0)
    {
        yield return new List<int>();
        if (maxSize > 0)
            for (int i = minIndex; i < list.Count; i++)
                foreach (var set in FindAllCombos(list, maxSize - 1, i + 1))
                {
                    set.Add(list[i]);
                    yield return set;
                }
    }
    

    Note that the elements of the output sets will here be in the reverse order.