0

I have n number of arrays and each array may contain n number of elements. I have to generate all possible combination of values by taking one element from each array.

I need help in C#/VB.NET language.

Below is an example.

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

I want the combinations as (There will be 3*2*3 = 18 combinations) a1x a1y a1z a2x a2y a2z b1x b1y b1z b2x b2y b2z c1x c1y c1z c2x c2y c2z

if I have 4 arrays, there will be 36 combinations. Arr1: ( a, b, c ) Arr2: ( 1, 2 ) Arr3: ( x, y, z ) Arr4: ( m, n )

Combinations:

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

0

2 Answers 2

7

Based on article by 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})); 
    }
}

The output:

(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)
Sign up to request clarification or add additional context in comments.

Comments

3

First method

You can use Nested For Loops

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

Second Method

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

1 Comment

The point is you don't know how many loops you need, you are given an arbitrary number of arrays, how do you hard code a certain deep loop to accommodate that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.