【问题标题】:Generate all possible combinations from multiple arrays (C#/VB.NET) [closed]从多个数组生成所有可能的组合(C#/VB.NET)[关闭]
【发布时间】:2013-02-01 18:22:28
【问题描述】:

我有 n 个数组,每个数组可能包含 n 个元素。我必须通过从每个数组中获取一个元素来生成所有可能的值组合。

我需要 C#/VB.NET 语言方面的帮助。

下面是一个例子。

Arr1: (a, b, c) Arr2: ( 1, 2 ) Arr3: (x, y, z)

我希望组合为(将有 3*2*3 = 18 种组合) a1x a1y a1z a2x a2y a2z b1x b1y b1z b2x b2y b2z c1x c1y c1z c2x c2y c2z

如果我有 4 个数组,就会有 36 个组合。 Arr1: (a, b, c) Arr2: ( 1, 2 ) Arr3: (x, y, z) Arr4: ( m, n )

组合:

a1xm a1xn a1ym a1yn a1zm a1zn …………………… ……………………

【问题讨论】:

    标签: c# vb.net


    【解决方案1】:

    基于Eric Lippert的文章

    void Main()
    {
        var set1 = new object[]{'a', 'b', 'c'};
        var set2 = new object[]{1,2,};
        var set3 = new object[]{'x', 'y', 'z'};
    
        string.Join(", ", new[] {set1, set2, set3}.CartesianProduct().Select(item => item.ToArray()).Select(item => string.Format("({0},{1},{2})", item[0], item[1], item[2]))).Dump();
    }
    
    
    public static class CartesianProductContainer
    {
        public 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})); 
        }
    }
    

    输出:

    (a,1,x), (a,1,y), (a,1,z), (a,2,x), (a,2,y), (a,2,z), (b,1,x), (b,1,y), (b,1,z), (b,2,x), (b,2,y), (b,2,z), (c,1,x), (c,1,y), (c,1,z), (c,2,x), (c,2,y), (c,2,z)
    

    【讨论】:

      【解决方案2】:

      第一种方法

      您可以使用Nested For Loops

      for (int i=0; i < Arr1.Length ; i++)
      {  
        for (int j=0; i < Arr2.Length ; j++)
        {  
           like this..............
        }  
      }  
      

      第二种方法

      C# - Most efficient way to iterate through multiple arrays/list

      【讨论】:

      • 关键是你不知道你需要多少个循环,你得到了任意数量的数组,你如何硬编码某个深度循环来适应它?
      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2017-04-16
      • 2016-08-16
      • 2016-01-07
      相关资源
      最近更新 更多