Search code examples
c#mathmultidimensional-arraycombinationscombinators

Finding permutations on 2D array


I have an 2D array like this.

1 2 3
2 3 4

Are there anyway to find all the combination that meet the requirement below ?

I want to find all the combination such as each number from a column must be selected.

Such as

{1,2,3}
{1,2,4}
{1,3,3}
{1,3,4}

{2,2,3}
{2,2,4}
{2,3,3}
{2,3,4}

I have no idea how to generate all the combination like above.

Many thanks.


Solution

  • A typical method to create combinations is a recursive algorithm where you slice one element off each time and calculate combinations for the tail.

    For example:

    public static IEnumerable<IEnumerable<int>> Combinations (int[,] array, int column)
    {
        if (column == array.GetLength(1)) 
        {
           yield return Enumerable.Empty<int>();
           yield break;
        };
    
        for(int j=0; j < array.GetLength(0); j++)
        {
            int v = array[j, column];
            var first = new List<int>{ v };
            foreach (var combination in Combinations(array, column+1))
            {
                yield return first.Concat(combination);
            }
        }
    }
    
    
    public static void Main()
    {
        int [,] a = new int [2,3] {
           {1, 2, 3} ,
           {2, 3, 4} ,
        };
    
        var result = Combinations(a, 0);
    
        foreach (var t in result)
        {
           Console.WriteLine(string.Join(",", t));
        }
    
    }