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?
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.
Answer and Explanation: The number of combinations that are possible with 20 numbers is 1,048,575.
We see that the number of combinations possible with 30 numbers, where no number can be repeated, is 1,073,741,823.
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(); } }
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With