Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LINQ to find all combinations of n items from a set of numbers?

I'm trying to write an algorithm to select all combinations of n values from a set of numbers.

For instance, given the set: 1, 2, 3, 7, 8, 9

All combinations of 2 values from the set is:

(1, 2), (1, 3), (1, 7), (1, 8), (1, 9), (2, 3), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (7, 8), (7, 9), (8, 9)

And 3 is:

(1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 7, 8), (3, 7, 9), (3, 8, 9), (7, 8, 9)

etc!

I'm currently using methods to to yield return sets of combinations of 2, 3 and 4 values, but it seems to me this could be generalised in a LINQ query.

Thanks for your help!

like image 958
Dink Avatar asked Oct 26 '15 00:10

Dink


People also ask

How use all in Linq C#?

All Method: The All method of System. LINQ. Queryable class returns a Boolean value if all the elements of the sequence satisfy the provided condition. It returns true if all the elements satisfy the condition otherwise it returns false.

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

Usage:

var results = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);

Code:

public static class Ex
{
    public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] {e}).Concat(c)));
    }
}
like image 115
user109260 Avatar answered Oct 22 '22 19:10

user109260