Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate Combinations of Elements of a List<T> in .NET 4.0

I have a question that is similar, but not identical, to the one answered here.

I would like a function generate all of the k-combinations of elements from a List of n elements. Note that I am looking for combinations, not permutations, and that we need a solution for varying k (i.e., hard-coding the loops is a no-no).

I am looking for a solution that is a) elegant, and b) can be coded in VB10/.Net 4.0.

This means a) solutions requiring LINQ are ok, b) those using the C# "yield" command are not.

The order of the combinations is not important (i.e., lexicographical, Gray-code, what-have-you) and elegance is favored over performance, if the two are in conflict.

(The OCaml and C# solutions here would be perfect, if they could be coded in VB10.)

like image 960
Michael Dorfman Avatar asked Jul 13 '09 14:07

Michael Dorfman


People also ask

How do you find a combination in Java?

We use the size() method to get the number of elements in the list. We set a constant value 2 to r, i.e., the number of items being chosen at a time. After that, we use the combination formula, i.e., fact(n) / (fact(r) * fact(n-r)) and store the result into the result variable.


1 Answers

Code in C# that produces list of combinations as arrays of k elements:

public static class ListExtensions
{
    public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        List<T[]> result = new List<T[]>();

        if (k == 0)
        {
            // single combination: empty set
            result.Add(new T[0]);
        }
        else
        {
            int current = 1;
            foreach (T element in elements)
            {
                // combine each element with (k - 1)-combinations of subsequent elements
                result.AddRange(elements
                    .Skip(current++)
                    .Combinations(k - 1)
                    .Select(combination => (new T[] { element }).Concat(combination).ToArray())
                    );
            }
        }

        return result;
    }
}

Collection initializer syntax used here is available in VB 2010 (source).

like image 142
Sergii Volchkov Avatar answered Oct 20 '22 05:10

Sergii Volchkov