c # cartesian product of arrays

0

I need to find a way to get all the combinations that can be obtained by taking an element from the first array and another from the second. I give an example so that it is understood ARRAY X = [A, B] ARRAY Y = [1,2]

results that you are looking to obtain or show A1 A2 B1 B2

in this case it has 2 elements, array A and B, but they could have 5 and 8 elements. As I get all the possible combinations, I am programming in c # and I need to find a way to combine several arrays.

    
asked by AlexH 23.03.2017 в 20:47
source

2 answers

0
    static string [] combinar(string [] primerArray, string [] segundoArray)
    {
        string[] resultado = new string[primerArray.Length * segundoArray.Length];
        int c = 0;
        for(int i=0; i<primerArray.Length;i++)
            for (int j = 0; j < segundoArray.Length; j++)
            {
                resultado[c] = primerArray[i] + segundoArray[j];
                c++;
            }
        return resultado;
    }
    
answered by 23.03.2017 / 21:07
source
2

Since another answer was accepted with a traditional implementation, I allow myself to add an answer for more general benefit.

Assuming you have the following 2 lists:

char[] charList = { 'A', 'B', 'C' };
int[] intList = { 1, 2, 3, 4 };

... these are the 2 options I know to obtain a Cartesian product using a single LINQ statement:

  • Using Enumerable.SelectMany ( Demo ):

    var productoCartesiano = 
        charList.SelectMany(c => intList.Select(n => string.Concat(c, n)));
    
  • Using Enumerabe.Join , but using it equivalent to a SQL CROSS JOIN or INNER JOIN ... ON 1=1 ( Demo ):

    var productoCartesiano = 
        charList.Join(intList, c => 1, n => 1, (c, n) => string.Concat(c, n));
    
  • answered by 24.03.2017 в 03:10