构建组合矩阵

Pet*_*nge 5 c# algorithm combinations permutation matrix

我确信这已被问了一百万次,但是当我搜索所有的例子都不太合适时,所以我想我还是应该问它.

我有两个数组,每个数组总共包含6个项目.例如:

string[] Colors=
    new string[] { "red", "orange", "yellow", "green", "blue", "purple" };

string[] Foods=
    new string[] { "fruit", "grain", "dairy", "meat", "sweet", "vegetable" };
Run Code Online (Sandbox Code Playgroud)

在这两个阵列之间,有36种可能的组合(例如"红色水果","红色颗粒").

现在我需要进一步将这些组合成六组唯一值.

例如:

meal[0]=
    new Pair[] { 
        new Pair { One="red", Two="fruit" }, 
        new Pair { One="orange", Two="grain" }, 
        new Pair { One="yellow", Two="dairy" }, 
        new Pair { One="green", Two="meat" }, 
        new Pair { One="blue", Two="sweet" }, 
        new Pair { One="purple", Two="vegetable" } 
    };
Run Code Online (Sandbox Code Playgroud)

在哪里吃饭

Pair[][] meal;
Run Code Online (Sandbox Code Playgroud)

在我的"餐"列表中不能重复任何元素.因此,只有一个"红色"项目和一个"肉"项目等.

我可以根据前两个数组轻松创建对,但我在如何最好地将它们组合成唯一组合方面做了一个空白.

Eri*_*ert 5

好的,你想要一个包含所有720种可能序列的序列.这有点棘手,但可以做到.

基本思路与我之前的答案相同.在那个答案中我们:

  • 随机产生一个排列
  • 使用未计算的第一个数组压缩置换的第二个数组
  • 从查询中生成一个数组

现在我们将做同样的事情,除了不是随机产生排列,我们将产生所有的排列.

首先获取此库:

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-CG

好的,我们需要做出六个项目的所有排列:

Permutations<string> permutations = new Permutations<string>(foods);
Run Code Online (Sandbox Code Playgroud)

我们想对每个排列做什么?我们已经知道了.我们想首先用颜色数组压缩它,将它变成一对数组,然后我们将它们变成一个数组.相反,让我们把它变成一个List<Pair>因为,好吧,相信我,它会更容易.

IEnumerable<List<Pair>> query = 
    from permutation in permutations
    select colors.Zip(permutation, (color, food)=>new Pair(color, food)).ToList();
Run Code Online (Sandbox Code Playgroud)

现在我们可以将该查询转换为结果列表;

List<List<Pair>> results = query.ToList();
Run Code Online (Sandbox Code Playgroud)

我们已经完成了.我们有一个包含720个项目的列表.每个项目都是一个包含6对的列表.

显然,繁重的工作是由图书馆代码完成的; 放在它上面的查询非常简单.

(一段时间以来,我想写一篇关于在LINQ中生成排列的方法的博客文章;我可能会以此为例!)