首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >家庭作业: Java中的魔法植物递归练习

家庭作业: Java中的魔法植物递归练习
EN

Stack Overflow用户
提问于 2017-11-02 14:07:29
回答 2查看 187关注 0票数 2

为了说明这一点,这是我的编程II类的分级作业。我通常很容易接受新的编程概念,但是这个关于递归的特殊任务确实让我感到失望,我正在寻找一些正确的方向。下面是逐字分配和我目前已有的代码。

魔术植物

我们有一种神奇的植物,一旦它被种植,它就在第一年发芽并长出两片叶子。它的叶子每年翻倍,除了每隔三年它的叶子翻倍。类似于:

编写一个名为MagicPlant的类,它包含以下方法:

  • 一种返回给定植物年龄的叶数的方法。
  • 一种非递归方法,它在给定叶数的情况下返回植物的年龄。
  • 一种递归方法,它返回给定叶数的植物的年龄。

在驱动程序类中测试方法。

找出您的算法和数据结构可以处理的最大(最老的)植物。

这就是我得到的结果,我在最后一个要点上遇到了麻烦,在第二个问题上也有点混乱(但我的代码似乎很有效)。

我的当前代码不包括驱动程序类,因为它只是调用语句:

代码语言:javascript
复制
public class MagicPlant {

    // Method that returns the number of leaves given
    // the age of the plant.
    public int getLeaves(int age) {
        int leafCount = 1;
        for (int i = 1; i <= age; i++) {
            if (i % 3 != 0) {
                leafCount *= 2;
            } else {
                leafCount *= 3;
            }
        }
        return leafCount;
    }

    // Non-recursive method that returns the age of the plant
    // given the number of leaves.
    public int getAgeNR(int leaves) {
        int age = 1;
        while (leaves > getLeaves(age)) {
            age++;
        }
        return age;
    }

    // Recursive method that returns the age of the plant
    // given the number of leaves.
    public int getAgeR(int leaves) {
        return 0;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-02 14:39:47

我的tipp是用递归替换while-loop。因此,您没有局部变量,而是将该变量返回到方法(递归)中。

另外,我建议您为递归创建两个方法:

代码语言:javascript
复制
public int getAgeR(int leaves){
     return getAgeR(1, leaves); // call overload with initial value
}

private int getAgeR(int age, int leaves){
     // do your magic here
}
票数 1
EN

Stack Overflow用户

发布于 2017-11-02 14:39:22

代码语言:javascript
复制
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
    if(leaves == 2) {
        return 1;
    }
    if(leaves % 3 == 0) {
        return getAgeR(leaves/3)+1;         
    } else {
        return getAgeR(leaves/2)+1;
    } 
}

这是数年的反义词。与其从一开始开始,你只需要从结束开始,并减少每一个循环循环。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47077299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档