Combinations of a generic collection

static class Combinatorial { private static IEnumerable<int> SetFromBits(int i) { for (var n = 0; i != 0; i /= 2, n++) if ((i & 1) != 0) yield return n; } public static IEnumerable<List<T>> Combinations<T>(this IReadOnlyList<T> list) { for (var i = 1; i < 1 << list.Count; i++) yield return SetFromBits(i).Select(n => list[n]).ToList(); } }
The list of possible combinations is extracted from the idea that the "1"s positions in the binary numbers are actually all the possible combinations of a collection.

Example (with a collection of 3 elements):
001, 010, 011, 100, 101, 110, 111
the combinations would be generated taking the elements from the collection placed in the positions of the "1"s in those 7 possibilities.

Usage:
var listExample = new List<string> { "A", "B", "C" };
var combs = listExample.Combinations();

Result (value of combs variable):
IEnumerable<List<String>> (7 items)
List<String> (1 item)
A
List<String> (1 item)
B
List<String> (2 items)
A
B
List<String> (1 item)
C
List<String> (2 items)
A
C
List<String> (2 items)
B
C
List<String> (3 items)
A
B
C

Beware: The number of possible combinations of a collection grow very quickly for larger collection sizes!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.