user1038502
user1038502

Reputation: 837

How to apply the yield to recursive functions

I have the following function which I would like to change to return an enumerable using the yield operator. I have never used that operator before and is a bit perplexed to why I cant get it to work.

    public static void printPermutations(int[] n, int[] states, int idx)
    {
        if (idx == n.Length)
        {
            Console.WriteLine(string.Join(", ", n));
            return;
        }
        for (int i = 0; i < states.Length; i++)
        {
            n[idx] = states[i];
            printPermutations(n, states, idx + 1);
        }
    }

I change the function to this, but then I get an System.IndexOutOfRangeException on n[idx] = states[i]; and I cant understand why.

    public static IEnumerable<int[]> printPermutations2(int[] n, int[] states, int idx)
    {
        if (idx == n.Length)
        { 
            yield return n;
        }
        for (int i = 0; i < states.Length; i++)
        {
            n[idx] = states[i];
            var perms = printPermutations2(n, states, idx + 1);
            foreach(var p in perms)
                yield return p;

        }
    }

Upvotes: 0

Views: 88

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26436

yield return does not exit the method - so your current code always runs the for loop.

Add a yield break to break out of the method:

if (idx == n.Length)
{ 
    yield return n;
    yield break;
}

Upvotes: 3

Related Questions