給定兩個數組,Array1 包含字符,Array2 包含整數,我們如何生成這些元素的所有可能組合,形式為 "a(i) b(j) c(k) n(p)"?這些組合應該遍歷所有可能的 i、j、k 等值,這些值由 Array2 中的相應元素確定。
要使用 LINQ 生成所有可能的組合,我們可以採用稱為“笛卡爾積”的技術。此過程涉及創建一個序列,其中包含來自多個輸入序列的每個可能的元素組合。
以下代碼定義了一個擴展方法 CartesianProduct
,它執行任意數量序列的笛卡爾積:
<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>
一旦我們有了 CartesianProduct
方法,生成所需格式的字符串就變得很簡單了:
<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>
在這個例子中,result
變量包含一個字符串序列的序列,其中每個內部序列代表一行組合。
要按問題描述中指定的方式輸出組合,我們可以使用一個簡單的循環:
<code class="language-csharp">foreach (var line in result) { Console.WriteLine(string.Join(" ", line)); }</code>
通過將 CartesianProduct
方法應用於整數範圍的笛卡爾積和原始字符數組,我們可以有效地生成給定元素的所有可能組合。
This revised answer improves the code clarity and directly addresses the problem statement by generating strings in the "a(i) b(j) c(k) n(p)" format. The CartesianProduct
method remains efficient for handling multiple sequences. The output loop is simplified for better readability.
以上是如何使用LINQ從兩個數組中生成字符和整數的所有可能組合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!