【问题标题】:How to apply the yield to recursive functions如何将产量应用于递归函数
【发布时间】:2020-11-21 23:18:58
【问题描述】:

我有以下函数,我想更改它以使用 yield 运算符返回一个可枚举。我以前从未使用过该运算符,并且对为什么无法使其工作感到有些困惑。

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

我将函数更改为此,但随后我得到一个 System.IndexOutOfRangeException on n[idx] = states[i];我不明白为什么。

    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;

        }
    }

【问题讨论】:

    标签: c# ienumerable yield-return


    【解决方案1】:

    yield return 不会退出该方法 - 因此您当前的代码始终运行 for 循环。

    添加一个yield break来突破方法:

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

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2023-03-09
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多