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!
Both answers are good but can be speeded up by eliminating memory allocations
For answer 1: Now 2.5x faster when calculating 5 from 60
Edit:
EnumerableEx.Return
is from the System.Interactive package.Answer 2: Now 3x faster when calculating 5 from 60
This results in answer 2 being 5x faster than answer 1 for 5 from 60.
Usage:
Code:
Though the above answer is very neat I came up with a solution which can be much faster depending on the collection size.