【问题标题】:Filling String list with a recursive method ( Recursive fill method ) [closed]用递归方法填充字符串列表(递归填充方法)[关闭]
【发布时间】:2021-01-15 21:35:12
【问题描述】:

我想编写一个递归方法,填充并返回一个String[] 随机球列表,其中“蓝色”或“红色”长度为n,其中n 是随机的奇数。

我编写这个方法是为了生成一个 1-10 范围内的奇数,用作递归方法的参数。

public int ranNum (int ranN) {
    int min = 1
    int max = 10
    
    Random r = new Random();
    
    ranN = min + r.nextInt((max - min)/2)*2;

    return ranN;
}

(随机奇数)方法对吗?递归方法如何实现?

【问题讨论】:

  • 你必须在你的函数中调用函数

标签: java arrays recursion methods


【解决方案1】:

递归函数是直接或通过任意数量的中间函数调用调用自身的函数。

第一步通常是考虑终止。在您的情况下,您希望从1 计数到n 或从n 计数到1。当函数终止时,您可以选择返回最终值(称为尾递归)或通过向上遍历调用堆栈开始构建答案。后者被使用,当你有一个很长的计算并且你只想要最后一个值(例如斐波那契数)。

然后在每个步骤中做工作:

String[] tailRecursion(int n, String[] accumulator, Random rnd)
{
    if(n == 0) {
        return accumulator;
    }
    accumulator[n-1] = rnd.nextBoolean() ? "red" : "blue";
    return tailRecursion(n-1, accumulator, rnd);
}

方法通过tailRecursion(10, new String[10], new Random())调用

【讨论】:

  • 我写的生成奇数(n)的方法对吗?
  • 似乎是正确的。但是您只想有两个结果,“蓝色”和“红色”,这里一个随机布尔值就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 2022-08-17
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多