Home >Backend Development >C++ >How to Generate All Possible Combinations of Characters and Integers from Two Arrays Using LINQ?
Answer
To generate all possible combinations with linq, we can use technology called "Descartes". This process involves creating a sequence, which contains each possible element combination from multiple input sequences.The following code defines an extension method
CartesianProduct
Generate string combination
<code class="language-csharp">static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item }) ); }</code>Once we have the
CartesianProduct
In this example, the
<code class="language-csharp">var arr1 = new[] { "a", "b", "c" }; var arr2 = new[] { 3, 2, 4 }; var result = from cpLine in CartesianProduct( from count in arr2 select Enumerable.Range(1, count).Select(i => i.ToString())) select cpLine.Zip(arr1, (x1, x2) => x2 + "(" + x1 + ")");</code>
Output combination
result
To output combinations specified in the description of the question, we can use a simple cycle:
This Revied Answer Improves The Code Clarity and Directly Addresses The Privem Statement by Generations in the "A (I) B (J)" Format. The
<code class="language-csharp">foreach (var line in result) { Console.WriteLine(string.Join(" ", line)); }</code>Method Remains Efficient for Handling Multiple sequences.
The above is the detailed content of How to Generate All Possible Combinations of Characters and Integers from Two Arrays Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!