明確にするために、これは、私のプログラミングIIクラス。私は一般に新しいプログラミングの概念を非常に簡単に受け入れてきましたが、再帰に関するこの特定の割り当ては本当に私を投げつけており、正しい方向にいくつかの良いナッジを探しています。以下は、割り当てられたものと、私が現在持っているコードです。
魔法の植物
魔法の植物があります最初の年に2つの葉を発芽させ、成長させます。 3年ごとに葉を3倍にすることを除いて、毎年葉を2倍にします。何かのようなもの:
次のメソッドを含むMagicPlantというクラスを作成します。
- 植物の年齢に応じて葉の数を返すメソッド
- 葉の数を指定して植物の年齢を返す非再帰的メソッド。
- 葉の数を指定して、植物の年齢を返す再帰的メソッド。
ドライバクラスでメソッドをテストします。
アルゴリズムとデータ構造が処理できる最大の(最も古い)プラントを調べます。
それが私に与えられたものであり、私は最後の箇条書きで問題を抱えているだけでなく、2番目の箇条書きで少し濁っています(しかし、うまくいくように見えるコードがあります)。
Driverクラスを除く私の現在のコードは、単に呼び出しステートメントです。
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;
}
}
回答:
回答№1は1私のtippは、交換することです while
-再帰付きループ。したがって、ローカル変数はありませんが、代わりにその変数をメソッドに戻します(再帰的)。
また、再帰のために2つの方法を作ることをお勧めします:
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
}
回答№2の場合は0
// 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;
}
}
これは、年を数えることの逆です。最初から始める代わりに、最後から始めて、繰り返しのループごとに減らす必要があります。