2013-04-15 22 views
0

我就在那里我可以有2个或多个阵列字符串值的问题的工作。串联2个或多个数组独特的组合在新的列表

与第一阵列开始,我需要采取的每个值并连接下一个阵列的所述第一值和从所述第三,第一和依此类推,直到所有可能的组合被组合。

实施例:

Array1 {'A', 'B'} 
Array2 {'C', 'D', 'E'} 
Array3 {'F', 'G', 'H'} 

输出将是

Row 1 = A, C, F 
Row 2 = A, C, G 
Row 3 = A, C, H 
Row 4 = A, D, F 
Row 5 = A, D, G 
Row 6 = A, D, H 

,以此类推,直到所有组合被完成。在这种情况下,它将是18种组合。

我已经使用字符串连接前值结合起来,但从来没有在这样一个过程,其中阵列的数量可能会改变,项目内的数目,以产生这种类型的输出。

回答

0

嵌套for循环的这样的工作:

for (int i=0;i<=Array1.Length;i++) 
{ 
    for (int j=0; j<=Array2.Length; j++) 
    { 
    for (int k=0;k<=Array3.Length; k++) 
     //output however Array1[i] + ", " + Array2[j] + ", " + Array3[k]; 
    } 
} 
+1

又是怎么回事,如果有另一个数组? – I4V

+0

这种方法将工作3个阵列,但它需要保持嵌套正阵列。这也会大大增加算法的复杂性。 –

0

你可以使用一个Cartesian Product算法列出所有的组合:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace CartesianProduct 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      char[] array1 = new char[] { 'A', 'B' }; 
      char[] array2 = new char[] { 'C', 'D', 'E' }; 
      char[] array3 = new char[] { 'F', 'G', 'H' }; 

      int iterations = array1.Length * array2.Length * array3.Length; 

      for (int i = 0; i < iterations; i++) 
      { 
       Console.WriteLine("{0}, {1}, {2}", array1[i % array1.Length], array2[i % array2.Length], array3[i % array3.Length]); 
      } 
      Console.WriteLine("Total iterations: " + iterations.ToString()); 
      Console.Read(); 
     } 
    } 
} 
2

Here就是答案

List<string[]> lists = new List<string[]>() 
{ 
    new[]{"A", "B"}, 
    new[]{"C", "D", "E"}, 
    new[]{"F", "G", "H"} 
}; 

var cp = lists.CartesianProduct(); 

foreach(var line in cp) 
{ 
    Console.WriteLine(String.Join(" ",line)); 
} 

public static partial class MyExtensions 
{ 
    //http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx 
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
    { 
     // base case: 
     IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() }; 
     foreach (var sequence in sequences) 
     { 
      var s = sequence; // don't close over the loop variable 
      // recursive case: use SelectMany to build the new product out of the old one 
      result = 
       from seq in result 
       from item in s 
       select seq.Concat(new[] { item }); 
     } 
     return result; 
    } 
} 
+0

使用LINQ的好解决方案! –

+1

谢谢!简单和容易实施,并伎俩。 – Blachlock