Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All Possible Combinations of a list of Values

I have a list of integers List<int> in my C# program. However, I know the number of items I have in my list only at runtime.

Let us say, for the sake of simplicity, my list is {1, 2, 3} Now I need to generate all possible combinations as follows.

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

Can somebody please help with this?

like image 343
Sach Avatar asked Oct 18 '11 05:10

Sach


People also ask

How do you find all the possible combinations of numbers?

Remember, the formula to calculate combinations is nCr = n! / r! * (n - r)!, where n represents the number of items, and r represents the number of items being chosen at a time. Let's look at an example of how to calculate a combination.

How many combinations of 20 items are there?

Answer and Explanation: The number of combinations that are possible with 20 numbers is 1,048,575.

How many combinations of 30 items are there?

We see that the number of combinations possible with 30 numbers, where no number can be repeated, is 1,073,741,823.


2 Answers

try this:

static void Main(string[] args) {      GetCombination(new List<int> { 1, 2, 3 }); }  static void GetCombination(List<int> list) {     double count = Math.Pow(2, list.Count);     for (int i = 1; i <= count - 1; i++)     {         string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');         for (int j = 0; j < str.Length; j++)         {             if (str[j] == '1')             {                 Console.Write(list[j]);             }         }         Console.WriteLine();     } } 
like image 82
ojlovecd Avatar answered Oct 11 '22 04:10

ojlovecd


Assuming that all items within the initial collection are distinct, we can try using Linq in order to query; let's generalize the solution:

Code:

public static IEnumerable<T[]> Combinations<T>(IEnumerable<T> source) {   if (null == source)     throw new ArgumentNullException(nameof(source));    T[] data = source.ToArray();    return Enumerable     .Range(0, 1 << (data.Length))     .Select(index => data        .Where((v, i) => (index & (1 << i)) != 0)        .ToArray()); } 

Demo:

  var data = new char[] { 'A', 'B', 'C' };    var result = Combinations(data);    foreach (var item in result)     Console.WriteLine($"[{string.Join(", ", item)}]"); 

Outcome:

[] [A] [B] [A, B] [C] [A, C] [B, C] [A, B, C] 

If you want to exclude the initial empty array, put .Range(1, (1 << (data.Length)) - 1) instead of .Range(0, 1 << (data.Length))

like image 44
Dmitry Bychenko Avatar answered Oct 11 '22 04:10

Dmitry Bychenko