我需要找到一个像这样工作的函数:
int[] matches = getAllPossibleCombinations(
int lengthOfEachIntReturnedInArray,
List<char> typesOfElementsUsedInCombinations);
输入元素如下(这只是一个示例):
-
int lengthofeachintreturnedinarray = (int) 2
-
List<char> typesofelementsusedincombinations = {a,b}
那么输出必须是(在字符串数组中):
aa
ab
ba
bb
数组中每个单独的输出元素必须具有由方法中的第一个参数定义的长度(在本例中为 2),并且必须包含第二个参数中给定字母之间的所有可能组合
我已经看到了一些关于 powersets 的内容,我应该使用它们,还是应该 foreach
循环适合这份工作吗?
!建议的问题与上面的答案不一样,它不使用设置长度!
最佳答案
我将引导您前往 Eric Lippert 的 article关于实现Cartesian Product在 Linq 中,他将其写为 extension method .
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}));
}
使用它,您可以像这样实现您的方法:
static IEnumerable<string> GetAllPossibleCombinations(
int lengthofeachintreturnedinarray,
IEnumerable<string> typesofelementsusedincombinations)
{
return Enumerable
.Repeat(typesofelementsusedincombinations, lengthofeachintreturnedinarray)
.CartesianProduct()
.Select(strings => String.Concat(strings));
}
关于c# - 一定数量的数字之间所有可能的组合c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18641458/