-1

Say I have following arrays of int:

var array1 = new[] {0, 2, 4, 6};
var array2 = new[] {0, 4, 5, 7};
var array3 = new[] {1, 4, 3, 5};

How do I merge this into one array of arrays so that the resulting is the list of all possible combinations of values in arrays? I.e. something similar to:

var resultingArray = new[] {new[] {0, 0, 1}, new[] {0, 4, 1}, new[] {0, 5, 1}....};

E.g. the length of arrays is the number of arrays I have but with the assumption that I do not know how many arrays I have and their length.

Azimuth
  • 2,599
  • 4
  • 26
  • 33

2 Answers2

2

You can´t merge them automatical and dynamic because your programm doesn´t know how manny and which arrays you got. But you can easyly create an Array of Arrays, because you can hardcode it, like this:

int resultingArray[][] = new int[3][]; // 3 = X maybe
resultingArray [0] = array1;
resultingArray [1] = array2;
resultingArray [2] = array3;
// ... up to X

It will look like this if you visualize the structure:

[[0,2,4,6], [...], [...]]
LenglBoy
  • 1,451
  • 1
  • 10
  • 24
2

This is known as the N-ary Cartesian Product.

Eric Lippert blogged a solution to this:

public static IEnumerable<IEnumerable<T>> Combine<T>(params IEnumerable<T>[] sequences)
{
    return Combine(sequences.AsEnumerable());
}

public static IEnumerable<IEnumerable<T>> Combine<T>(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 }));
}

This is how you could use it:

var array1 = new[] { 0, 2, 4, 6 };
var array2 = new[] { 0, 4, 5, 7 };
var array3 = new[] { 1, 4, 3, 5 };

var result = var result = Combine(array1, array2, array3);

var combinations = result.Select(x => x.ToArray()).ToArray();

foreach (var combination in combinations)
    Console.WriteLine(string.Join(", ", combination));

Note that you don't actually need to convert the resulting enumerables into arrays like I did above, unless you need to pass them to methods that expect arrays.

You can use result directly like so:

foreach (var combination in result)
    Console.WriteLine(string.Join(", ", combination));
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • But you need to enter all base-arrays by their name and you can´t do this manually. So this is very overloaded and complicated to read. But one way to do it. – LenglBoy Apr 11 '18 at 13:04
  • Is there a generic solution? Say I don't know how many array I have and how long they are. – Azimuth Apr 11 '18 at 13:08
  • @Azimuth This *is* a generic solution. You can pass any number of arrays of any length (each array could be a different length). – Matthew Watson Apr 11 '18 at 13:08
  • What about int[][]? Or is that something else? – Frontear Apr 11 '18 at 13:21