>使用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中文网其他相关文章!