矩阵列组合的c#递归

时间:2016-06-13 18:25:44

标签: c# loops recursion matrix

我有K组的MxN矩阵。组是一组列。如何生成一组与另一组的列的组合?
例如2x4矩阵,组大小 - 2列(1,2 - 第一,3,4 - 秒)
我得到组合
1 - 3
1 - 4
2 - 3
2 - 4
在这种情况下,我可以使用多个循环

for (int i = 0; i < 2; i++)
    for (int j = 2; j < 4; j++)
        Console.WriteLine("{0} - {1}", i, j);

3组和2x6矩阵的情况怎么样?

for (int i = 0; i < 2; i++)
    for (int j = 2; j < 4 ; j++)
        for (int k = 4; k < 6; k++)
            Console.WriteLine("{0} - {1} - {2}", i, j, k);

其他案件怎么样?如何组织循环/递归?

1 个答案:

答案 0 :(得分:1)

在此问题中不确定行的边缘情况和行的作用,但对于您提供的简单情况,这将有效:

    static void Main()
    {
        var columns = 6;
        var groupSize = 2;

        var groups = GetGroups(columns, groupSize).ToArray();

        var groupCurrentIndex = Enumerable.Range(0, groups.Length).ToDictionary(i => i, i => 0);
        var maxIndex = groupSize - 1;

        while (true)
        {
            var combination = groups.Select((g, i) => g[groupCurrentIndex[i]]);
            PrintCombination(combination);

            var incrementedGroupIndex = false;
            for (var i = groups.Length - 1; i > 0; i--)
            {
                if (groupCurrentIndex[i] != maxIndex)
                {
                    groupCurrentIndex[i]++;
                    incrementedGroupIndex = true;
                    break;
                }
                if (groupCurrentIndex[i] == maxIndex && groupCurrentIndex[i - 1] != maxIndex)
                {
                    groupCurrentIndex[i-1]++;
                    incrementedGroupIndex = true;

                    for (var j = i; j < groups.Length; j++)
                    {
                        groupCurrentIndex[j] = 0;
                    }
                    break;
                }
            }
            if (!incrementedGroupIndex)
            {
                break;
            }
        }

        Console.ReadLine();
    }

    private static IEnumerable<int[]> GetGroups(int columns, int groupSize)
    {
        for (var startIndex = 0; startIndex < columns; startIndex = startIndex + groupSize)
        {
            yield return Enumerable.Range(startIndex, groupSize).ToArray();
        }
    }

    private static void PrintCombination(IEnumerable<int> combination)
    {
        Console.WriteLine(string.Join(" - ", combination));
    }