for循环动态/递归?

时间:2019-02-07 10:07:40

标签: c# recursion dynamic

我有一个问题,我有6个for循环,但我想删除循环并用递归/动态方法替换它们。.可悲的是,我不知道如何做到这一点。 也许你们中的一个可以帮助我。

for (int a = 1; a < 45; a++)
                {
                    for (int b = a + 1; b < 46; b++)
                    {
                        for (int c = b + 1; c < 47; c++)
                        {
                            for (int d = c + 1; d < 48; d++)
                            {
                                for (int e = d + 1; e < 49; e++)
                                {
                                    for (int f = e + 1; f < 50; f++)
                                    {                                           
                                        counter++;
                                        new_counter = zaehler.ToString("N0");
                                        Console.WriteLine(a + " " + b + " " + c + " " + d + " " + e + " " + f + " | -> " + new_counter);
                                        if (zaehler == 13983816)
                                        {
                                            Console.ForegroundColor = ConsoleColor.Green;
                                            Console.WriteLine($"{new_counter} combinations.");
                                            Console.ReadKey();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

1 个答案:

答案 0 :(得分:2)

这里的总体意图有点难以理解,但这是一个动态递归的版本,它似乎可以做类似的事情;我还没有完全检查它的等效性:

static void RunLoop(int depth, int from, int to, Action<int, int[]> callback)
{
    int[] tokens = new int[depth];
    int counter = 0;
    RunLoop(tokens, 0, from, to, callback, ref counter);
}
private static void RunLoop(int[] tokens, int index, int from, int to,
    Action<int, int[]> callback, ref int counter)
{
    int nextIndex = index + 1;
    for(int i = from; i < to; i++)
    {
        tokens[index] = i;
        if (nextIndex == tokens.Length)
        {
            callback(counter, tokens);
            counter++; // post-increment when invoking the callback
        }
        else
        {
            counter++; // pre-increment when diving
            RunLoop(tokens, nextIndex, i + 1, to + 1, callback, ref counter);
        }
    }
}

用法:

public static void Main()
{
    RunLoop(6, 1, 45, (i, arr) => Console.WriteLine(i + ": " + string.Join(", ", arr)));
}

您的“到达最深处时的操作”在callback中;第一个参数是到目前为止的总计数器,第二个参数是组成该值的连续标记。