2017-11-12 5 views
-6

「モバイルはロッドまたはボブのいずれかである」ロッドには2つのより単純なモバイルが含まれているボブにはモバイルは含まれていない。モービルズでは、ボブのケースとロッドのケースが必要です。ロッドケースでは、2つの再帰呼び出しを行う再帰的ケースをコーディングします。たとえば、ウェイトを定義する方法を理解する必要がありますあなたがサポートしている2つのモビールの重量の点では、棒の場合です。ボブのケースでは、再帰のないベースケースをコーディングします。私は方法のスタブを変更することはできません、それらの中に含まれているものだけ、私はisBalanced()メソッドを開始しようとしましたが、私は実際にどこに行くのか分かりません。ロッドは、その左端の距離と左端から垂れ下がっている重りの積が、その右端の距離と右端から垂れ下がっている重さとの積に等しいときに、バランスが取られます。上記のモバイルのすべてのロッドはバランスが取れているので、モバイル全体がバランスを保っていると言います。誰かが正しい方向に私を指すことができるなら、私はそれを高く評価します。携帯電話がバランスしているかどうかを判断するための再帰

/** 
* A Mobile is either a Bob or Rod. 
* 
* A Bob is a Mobile consists of a weight hanging from a vertical wire. 
* 
* Here's a diagram, where W denotes a weight: 
* 
* <pre> 
*        | 
*        W 
* </pre> 
* 
* A Rod is a Mobile that consists of a horizontal rod that has one Mobile hanging from its left end and another Mobile 
* hanging from its right end. The rod is hanging from a vertical wire. The distance along the rod from the vertical 
* wire to the left end is called the left length, and the distance from the vertical wire to the right end is called 
* the right length. 
* 
* Here's a diagram: 
* 
* <pre> 
*      _____|__________ 
*      |    | 
*      L    R 
* </pre> 
* 
* The left length is 5 and the right length is 10. L and R are the left and right Mobiles, respectively. 
*/ 
public class Mobile 
{ 
/** 
* True if the Mobile is a Bob; false if the Mobile is a Rod. 
*/ 
private boolean isBob; 

/** 
* If isBob is true, contains the weight of the Bob. 
*/ 
private int weight; 

/** 
* If isBob is false, contains the left length of the Rod. 
*/ 
private int leftLength; 

/** 
* If isBob is false, contains the right length of the Rod. 
*/ 
private int rightLength; 

/** 
* If isBob is false, contains the left Mobile of the Rod. 
*/ 
private Mobile left; 

/** 
* If isBob is false, contains the right Mobile of the Rod. 
*/ 
private Mobile right; 

/** 
* Creates a Bob with the given weight. 
*/ 
public Mobile (int weight) 
{ 
    this.isBob = true; 
    this.weight = weight; 
} 

/** 
* Creates a Rod of the given configuration. 
*/ 
public Mobile (int leftLength, int rightLength, Mobile left, Mobile right) 
{ 
    this.isBob = false; 
    this.leftLength = leftLength; 
    this.left = left; 
    this.rightLength = rightLength; 
    this.right = right; 
} 

public boolean isBalanced() 
{ 
    return false; 
} 

答えて

0

まず、MobileクラスをRodとBobの異なるサブクラスに分割します。次のステップでは、両方の型に対して異なるisBalanced()メソッドを定義できます。ボブは常にバランスがとれています。ロッドの場合、左右のモバイルを再帰的に分析する必要があります。再帰は、ボブに実行されると自動的に停止します。 モバイルが平衡しているかどうかを判断する必要のある左右のモバイルの総重量も、再帰的に計算する必要があります。

関連する問題