c# - 递归代替多个嵌套的 for 循环?

标签 c# c#-4.0 recursion

我在尝试更新嵌套 for 循环以改用递归时遇到了一些问题。使用递归时是否可以从早期的 for 循环访问 a、b 和 c 变量?下面是我尝试将其转换为递归调用的简单示例。

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

编辑:解决方案需要能够在运行时进行调整,以便用户可以选择需要多少级别。

最佳答案

这是一个递归解决方案(使用 functional programming 样式):

public static IEnumerable<IEnumerable<int>> GetCombinations(IEnumerable<int> limits)
{
    if (limits.Any() == false)
    {
        // Base case.
        yield return Enumerable.Empty<int>();
    }
    else
    {
        int first = limits.First();
        IEnumerable<int> remaining = limits.Skip(1);
        IEnumerable<IEnumerable<int>> tails = GetCombinations(remaining);

        for (int i = 0; i < first; ++i)
            foreach (IEnumerable<int> tail in tails)
                yield return Yield(i).Concat(tail);
    }
}

// Per http://stackoverflow.com/q/1577822
public static IEnumerable<T> Yield<T>(T item)
{
    yield return item;
}

示例使用:

var sequences = GetCombinations(new [] { 5, 3, 2, 4 /* ... */ });
foreach (var sequence in sequences)
    Console.WriteLine(string.Join(", ", sequence));

/* Output:
0, 0, 0, 0
0, 0, 0, 1
0, 0, 0, 2
0, 0, 0, 3
0, 0, 1, 0
0, 0, 1, 1
0, 0, 1, 2
0, 0, 1, 3
0, 1, 0, 0
0, 1, 0, 1
0, 1, 0, 2
... */

针对OP的具体场景(添加数组到collection):

var sequences = GetCombinations(new [] { 10, 20, 10 });
collection.AddRange(sequences.Select(s => s.ToArray()));

关于c# - 递归代替多个嵌套的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914299/

相关文章:

c# - 如何最小起订量使用工作单元和存储库模式的简单添加功能

c# - .net 请求浏览器版本不一致

c# - 将耗时的进程从我的 ASP.NET 应用程序中移走

c# - 等待多个后台线程

linq - 递归地从树中删除项目

c# - 在构建后事件中更新本地 nuget 包

c# - 为 strcmp() 上的溢出传递参数

c# - Linq - 高级 .OrderBy

python - 当我有一个唯一列表时,如何停止该函数?

Java 递归泛型和通配符