Recursion in place of multiple nested for loops?

允我心安 提交于 2019-12-30 10:03:15

问题


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

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


回答1:


Ok, try with this

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

Usage is like this AddToCollectionRecursive(collection, 10, 20, 10);.




回答2:


Here's a recursive solution (using a functional programming style):

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

Sample use:

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
... */

For OP's specific scenario (adding arrays to collection):

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



回答3:


something like this will work:

public void CreateIndexes(int a, int b, int c, Collection collection)
{
    if(c == 10) {b++; c = 0;}
    if(b == 20) {a++; b = 0;}
    if(a == 10) return;

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

    CreateIndexes(a, b, c, collection);
}



回答4:


Off the top of my head, i.e. not tested, something like this might work:

    List<int[]> collection = new List<int[]>();
    private void AddValues(int a, int b, int c)
    {

        collection.Add(new[] { a, b, c });

        if (c < 10)
        {
            c++;
            AddValues(a, b, c);
        }

        if (b < 20)
        {
            b++;
            c = 0;
            AddValues(a, b, c);   
        }

        if (a < 10)
        {
            a++;
            b = 0;
            c = 0;
            AddValues(a, b, c);
        }
    }

Start it by calling:

AddValues(0, 0, 0);



回答5:


Well, i think that if u resolve this problem using recursion, it will consume more memory and other resources!

But there is my suggestion:

private void FunctionName(int a, int b, int c, List<int[]> list)
{
    if (a<10)
    { 
       if (b<20)
       {
           if (c<10)
           {
               list.Add(new[] { a, b, c });
               c++;
               FunctionName(a,b,c,list);
            }
            else
            {
                 c=0;
                 b++;
                 FunctionName(a,b,c,list);
            }
       }
       else
       {
          b=0;
          a++;
          FunctionName(a,b,c,list);
       }
    }
 }

You call like this : FunctionName(0,0,0,list).

Hope it works! ^^



来源:https://stackoverflow.com/questions/18914299/recursion-in-place-of-multiple-nested-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!