c# - 一定数量的数字之间所有可能的组合c#

标签 c# .net string combinations combinatorics

我需要找到一个像这样工作的函数:

 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/

相关文章:

c# - WinRT - TCP 客户端?

c# - LINQ 到实体 : Loading One-To-Many Navigation Properties in Strong Typed Projections

c - 为什么我的解析函数返回不返回所有预期的标记?

python - 程序卡在 while 循环不打印

ruby - 如何将 Ruby 字符串强制为 n 个字符

c# - 在运行时编译程序集并将dll保存在文件夹中

c# - 绕过/忽略 Exchange 服务器 "Maximum Send Size"?

c# - 为什么C#中没有const成员方法和const参数?

c# - Entity Framework - 如何将连接字符串更改为相对的?

.net - 我可以使用数据注释通过 Entity Framework 4.1 RC 执行级联删除吗?