Search code examples
c#subsetpowerset

Algorithm for Power Set / Sub-Set combinations required, but only for a fixed number of elements


It is an extension of this problem - Super set in a list:

Getting all possible combinations from a list of numbers

This helps, but returns all sub-sets: http://rosettacode.org/wiki/Power_set#C.23

But what I need is to retrieve only the sub-sets that have a fixed number. I.e. say my list is a collection of numbers:

1 2 3 4 5 6

I only want the different combinations for an exact 4 numbers, i.e. 1,2,3,4 1,2,3,5 1,2,3,6 1,3,4,5 1,3,4,6 1,4,5,6 2,3,4,5 2,3,4,6 2,4,5,6 3,4,5,6

I am using numbers as an example, but in my solution I am dealing with other types of objects.


Solution

  • You can extend the solution you referenced by filtering on the length of the results

    public IEnumerable<IEnumerable<T>> GetPowerSetOfLength<T>(List<T> list, int length)
    {
        return from m in Enumerable.Range(0, 1 << list.Count)
                  //because doing a count will iterate through the enumerable 
                  //better to just convert it to a list up front 
                  let setResult = ( from i in Enumerable.Range(0, list.Count)
                                    where (m & (1 << i)) != 0
                                    select list[i]).ToList()
                  where setResult.Count==length
                  select setResult;
    }
    

    Here's a link to a dot net fiddle that is using this code if you want to test it out