递归代替多重嵌套for循环? [英] Recursion in place of multiple nested for loops?

查看:311
本文介绍了递归代替多重嵌套for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林具有尝试更新一个嵌套的循环使用递归代替一些问题。是有可能使用递归何时从for循环较早访问的a,b和c变量? 。下面是什么我尝试转换成一个递归调用一个简单的例子

Im having some issues with trying to update a nested for loop to use recursion instead. Is it possible to access the a,b and c variables from the earlier for loops when using recursion? Below is a simple example of what im trying to convert into a recursive call.

for(int a= 0; a < 10; a++)
{
    for(int b = 0; b < 20; b++)
    {
        for(int c = 0; c < 10; c++)
        {
            int[] indexes = new int[3]{a,b,c}
            collection.add(indexes);
        }
    }
}



编辑:该解决方案需要能够在运行时进行调整,使得用户可以选择多少个层次是必需的。

The solution needs to be able to be adjusted at runtime, such that a user can select how many levels are required.

推荐答案

好吧,试试这个

static void AddToCollectionRecursive(
    List<int[]> collection,
    params int[] counts)
{
    AddTo(collection, new List<int>(), counts, counts.Length - 1);
}

static void AddTo(
    List<int[]> collection,
    IEnumerable<int> value,
    IEnumerable<int> counts,
    int left)
{
    for (var i = 0; i < counts.First(); i++)
    {
        var list = value.ToList();

        list.Add(i);

        if (left == 0)
        {
            collection.Add(list.ToArray());
        }
        else
        {
            AddTo(collection, list, counts.Skip(1), left - 1);
        }
    }
}



用法是这样的 AddToCollectionRecursive(收集,10,20,10);

这篇关于递归代替多重嵌套for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆