可能的组合 [英] Possible combinations
本文介绍了可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表数组
List<string>[] possibleLines;
数组可以具有不同的大小,而且每个List <>可以具有不同数量的字符串.前例
Array can be of different size also each each List<> can have different number of strings. Fore example
-
List<string>[0]
-可以包含字符串第一个字符串",第二个字符串" -
List<string>[1]
-第三字符串",第四字符串",第五字符串"
List<string>[0]
- can have strings "first string", "second string"List<string>[1]
- "third string", "fourth string", "fifth string"
我需要获取所有可能的组合,每个字符串必须来自不同的列表(数组大小可能不同).例如
I need to get all possible combinations, each string must be from different list (array size may differ). For example
- 第一字符串",第四字符串"
- 第一个字符串",第五个字符串"
- 第二个字符串",第四个字符串"
以此类推.
推荐答案
您在这里正在计算未知数量集合的笛卡尔乘积.埃里克·利珀特(Eric Lippert)在
What you're doing here is computing the Cartesian Product of an unknown number of collections. Eric Lippert describes how to write a solution to this problem in this blog post (which I strongly suggest you read to see how he comes up with this solution).
他最终得到的代码是:
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}));
}
这篇关于可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文