>使用linq從多個數組中生成所有可能的組合:笛卡爾產品方法
>本文演示瞭如何利用Linq(語言集成查詢),以使用笛卡爾產品有效地從多個陣列中生成所有可能的組合。 所需的輸出格式是遵循模式a(i) b(j) c(k) n(p)
的字符串表示形式,其中i
,j
,k
和p
>是每個數組定義的範圍內的索引。
了解笛卡爾產品>
linq實現
以下LINQ代碼生成所需的組合:
中的每個元素都定義了
<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 cpLine.Zip(arr1, (x1, x2) => x2 + x1); // Helper function (implementation below) public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(params IEnumerable<IEnumerable<T>>[] sequences) { ... } </code>>創建最終輸出字符串結合在一起。
CartesianProduct
arr2
助手函數arr2
arr1
>
Zip
這是arr1
函數的可能實現:
此函數遞歸計算任意數量的輸入序列的笛卡爾產物。 CartesianProduct
CartesianProduct
<code class="language-csharp">public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(params IEnumerable<IEnumerable<T>>[] sequences) { if (sequences == null) throw new ArgumentNullException(nameof(sequences)); IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new[] { item }) ); }</code>
這有效地展示了Linq的力量,以簡明而優雅地產生來自多個陣列的所有可能組合。
以上是如何使用linq使用笛卡爾產品從多個陣列中生成所有可能的組合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!