【问题标题】:all possible combinations between certain amount of digits c#一定数量的数字c#之间的所有可能组合
【发布时间】:2013-09-09 14:10:44
【问题描述】:

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

 int[] matches = getAllPossibleCombinations(
    int lengthOfEachIntReturnedInArray, 
    List<char> typesOfElementsUsedInCombinations);

输入元素是这些(这只是一个例子):

  • int lengthofeachintreturnedinarray = (int) 2
  • List&lt;char&gt; typesofelementsusedincombinations = {a,b}

那么输出必须是(在字符串数组中):

ab

bb

数组中的每个单独的输出元素必须具有由方法中的第一个参数定义的长度(在本例中为 2),并且必须包含第二个参数中给定字母之间的所有可能组合

我看到了一些关于 powerset 的东西,我应该使用它们,还是应该 foreach 循环适合这项工作?

!建议的问题与上面的答案不一样,它不使用设置长度!

【问题讨论】:

  • 你有什么要求这样做
  • 与原子结合(化学)
  • 您希望第二个参数是 List&lt;string&gt; 还是 List&lt;char&gt; ?即,单个元素可以有多个字符吗?
  • 你是对的 - 我将其更改为 List ;谢谢!

标签: c# .net string combinations combinatorics


【解决方案1】:

我将引导您访问 Eric Lippert 的 article,了解如何在 Linq 中实现 Cartesian Product,他将其写为 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));
}

【讨论】:

  • 这将完全返回上面提到的值?
  • @user2698666 是的,会的。
  • 我尝试了代码,但它在第二个代码块的 .CartesianProduct() 行抛出错误:“错误 1 ​​'System.Collections.Generic.IEnumerable>' 不包含 'CartesianProduct' 的定义,并且没有扩展方法 'CartesianProduct' 接受类型为 'System.Collections.Generic.IEnumerable>' 的第一个参数发现“我该如何解决这个问题?
  • @user2698666 这是一个extension method。要像这样使用它,必须将它定义为静态类中的公共(或内部)静态方法。您可能还需要包含对类名称空间的引用。如果您不想将其用作扩展方法,请将其用作普通静态方法:CartesianProduct(Enumerable.Repeat(...)).Select(...);
猜你喜欢
  • 1970-01-01
  • 2019-11-18
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多