简体   繁体   English

在二维数组上查找排列

[英]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.非常感谢。

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));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM