给定两个数组,Array1 包含字符,Array2 包含整数,我们如何生成这些元素的所有可能组合,形式为 "a(i) b(j) c(k) n(p)"?这些组合应该遍历所有可能的 i、j、k 等值,这些值由 Array2 中的相应元素确定。
要使用 LINQ 生成所有可能的组合,我们可以采用称为“笛卡尔积”的技术。此过程涉及创建一个序列,其中包含来自多个输入序列的每个可能的元素组合。
以下代码定义了一个扩展方法 CartesianProduct
,它执行任意数量序列的笛卡尔积:
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 }) ); }
一旦我们有了 CartesianProduct
方法,生成所需格式的字符串就变得很简单了:
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 + ")");
在这个例子中,result
变量包含一个字符串序列的序列,其中每个内部序列代表一行组合。
要按问题描述中指定的方式输出组合,我们可以使用一个简单的循环:
foreach (var line in result) { Console.WriteLine(string.Join(" ", line)); }
通过将 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中文网其他相关文章!