Recursion in place of multiple nested for loops?

前端 未结 5 1629
日久生厌
日久生厌 2021-01-14 02:05

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 usin

5条回答
  •  無奈伤痛
    2021-01-14 03:07

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

    public static IEnumerable> GetCombinations(IEnumerable limits)
    {
        if (limits.Any() == false)
        {
            // Base case.
            yield return Enumerable.Empty();
        }
        else
        {
            int first = limits.First();
            IEnumerable remaining = limits.Skip(1);
            IEnumerable> tails = GetCombinations(remaining);
    
            for (int i = 0; i < first; ++i)
                foreach (IEnumerable tail in tails)
                    yield return Yield(i).Concat(tail);
        }
    }
    
    // Per http://stackoverflow.com/q/1577822
    public static IEnumerable Yield(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()));
    

提交回复
热议问题