Home >Backend Development >C++ >How to Generate All Possible Combinations from a Runtime-Sized List in C#?
Generate all possible combinations from a runtime-sized list of values
In a typical programming scenario, you will encounter a situation where you need to generate all possible combinations of elements from a given list of integers. To achieve this in C#, follow these steps:
List<int>
to accommodate any number of elements at runtime. The following is a sample code that implements this algorithm:
<code class="language-csharp">using System; using System.Collections.Generic; public class CombinationGenerator { public static void Main(string[] args) { GenerateCombinations(new List<int> { 1, 2, 3 }); } public static void GenerateCombinations(List<int> list) { int count = (int)Math.Pow(2, list.Count); for (int i = 1; i < count; i++) { List<int> combination = new List<int>(); string binary = Convert.ToString(i, 2).PadLeft(list.Count, '0'); for (int j = 0; j < binary.Length; j++) { if (binary[j] == '1') { combination.Add(list[j]); } } Console.WriteLine(string.Join(", ", combination)); } } }</code>
Using this algorithm you can efficiently generate all possible combinations of elements in a list, regardless of their size.
The above is the detailed content of How to Generate All Possible Combinations from a Runtime-Sized List in C#?. For more information, please follow other related articles on the PHP Chinese website!