Amitd Amitd - 1 month ago 20
C# Question

Generating all Possible Combinations

Given 2 arrays

Array1 = {a,b,c...n}
and
Array2 = {10,20,15....x}
how can I generate all possible combination as Strings a(i) b(j) c(k) n(p)
where

1 <= i <= 10, 1 <= j <= 20 , 1 <= k <= 15, .... 1 <= p <= x


Such as:

a1 b1 c1 .... n1
a1 b1 c1..... n2
......
......
a10 b20 c15 nx (last combination)


So in all total number of combination = product of elements of
array2 =
(10 X 20 X 15 X ..X x)


Similar to a Cartesian product, in which the second array defines the upper limit for each element in first array.

Example with fixed numbers,

Array x = [a,b,c]
Array y = [3,2,4]


So we will have 3*2*4 = 24 combinations. Results should be:

a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b1 c4

a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b2 c4


a2 b1 c1
a2 b1 c2
a2 b1 c3
a2 b1 c4

a2 b2 c1
a2 b2 c2
a2 b2 c3
a2 b2 c4


a3 b1 c1
a3 b1 c2
a3 b1 c3
a3 b1 c4

a3 b2 c1
a3 b2 c2
a3 b2 c3
a3 b2 c4 (last)

max max
Answer
using System;
using System.Text;

public static string[] GenerateCombinations(string[] Array1, int[] Array2)
{
    if(Array1 == null) throw new ArgumentNullException("Array1");
    if(Array2 == null) throw new ArgumentNullException("Array2");
    if(Array1.Length != Array2.Length)
        throw new ArgumentException("Must be the same size as Array1.", "Array2");

    if(Array1.Length == 0)
        return new string[0];

    int outputSize = 1;
    var current = new int[Array1.Length];
    for(int i = 0; i < current.Length; ++i)
    {
        if(Array2[i] < 1)
            throw new ArgumentException("Contains invalid values.", "Array2");
        if(Array1[i] == null)
            throw new ArgumentException("Contains null values.", "Array1");
        outputSize *= Array2[i];
        current[i] = 1;
    }

    var result = new string[outputSize];
    for(int i = 0; i < outputSize; ++i)
    {
        var sb = new StringBuilder();
        for(int j = 0; j < current.Length; ++j)
        {
            sb.Append(Array1[j]);
            sb.Append(current[j].ToString());
            if(j != current.Length - 1)
                sb.Append(' ');
        }
        result[i] = sb.ToString();
        int incrementIndex = current.Length - 1;
        while(incrementIndex >= 0 && current[incrementIndex] == Array2[incrementIndex])
        {
                current[incrementIndex] = 1;
                --incrementIndex;
        }
        if(incrementIndex >= 0)
            ++current[incrementIndex];
    }
    return result;
}