Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to find all combinations of items in an array?

Tags:

c#

algorithm

What is the best way to find all combinations of items in an array in c#?

like image 277
Bravax Avatar asked Dec 23 '09 11:12

Bravax


People also ask

How do you find all possible combinations?

To calculate combinations, we will use the formula nCr = n! / r! * (n - r)!, where n represents the total number of items, and r represents the number of items being chosen at a time. To calculate a combination, you will need to calculate a factorial.

How do you find all permutations of an array?

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.


1 Answers

UPDATED

Here are a set of generic functions (require .net 3.5 or higher) for different scenarios. The outputs are for a list of {1, 2, 3, 4} and a length of 2.

Permutations with repetition

static IEnumerable<IEnumerable<T>>      GetPermutationsWithRept<T>(IEnumerable<T> list, int length) {     if (length == 1) return list.Select(t => new T[] { t });     return GetPermutationsWithRept(list, length - 1)         .SelectMany(t => list,              (t1, t2) => t1.Concat(new T[] { t2 })); } 

Output:

{1,1} {1,2} {1,3} {1,4} {2,1} {2,2} {2,3} {2,4} {3,1} {3,2} {3,3} {3,4} {4,1} {4,2} {4,3} {4,4} 

Permutations

static IEnumerable<IEnumerable<T>>     GetPermutations<T>(IEnumerable<T> list, int length) {     if (length == 1) return list.Select(t => new T[] { t });     return GetPermutations(list, length - 1)         .SelectMany(t => list.Where(o => !t.Contains(o)),             (t1, t2) => t1.Concat(new T[] { t2 })); } 

Output:

{1,2} {1,3} {1,4} {2,1} {2,3} {2,4} {3,1} {3,2} {3,4} {4,1} {4,2} {4,3} 

K-combinations with repetition

static IEnumerable<IEnumerable<T>>      GetKCombsWithRept<T>(IEnumerable<T> list, int length) where T : IComparable {     if (length == 1) return list.Select(t => new T[] { t });     return GetKCombsWithRept(list, length - 1)         .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) >= 0),              (t1, t2) => t1.Concat(new T[] { t2 })); } 

Output:

{1,1} {1,2} {1,3} {1,4} {2,2} {2,3} {2,4} {3,3} {3,4} {4,4} 

K-combinations

static IEnumerable<IEnumerable<T>>      GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable {     if (length == 1) return list.Select(t => new T[] { t });     return GetKCombs(list, length - 1)         .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),              (t1, t2) => t1.Concat(new T[] { t2 })); } 

Output:

{1,2} {1,3} {1,4} {2,3} {2,4} {3,4} 
like image 71
Pengyang Avatar answered Sep 20 '22 08:09

Pengyang