递归计算移动设备是否平衡



任务的一些背景:"Mobile是一个rod或bob。rod包含两个更简单的Mobiles。bob不包含任何Mobile。当你在Mobiles上实现一个方法时,你需要有一个bob的case和一个rods的case。在rod的情况下,你将编码一个递归case,该递归case进行两次递归调用。例如,你需要弄清楚如何根据t的权重来定义rod的权重它支持两个Mobiles。在bob的情况下,您将编写一个没有递归的基本情况。"我不能改变这些方法的存根,只能改变其中包含的内容。我试着启动isBalanced ()方法,但我真的不知道我要去哪里。当一根棍子的左距离和左端悬挂的重量的乘积等于右距离和右端悬挂的重量的乘积时,它就是平衡的。上面显示的移动设备中的每根棍子都是平衡的,所以我们ay,移动设备作为一个整体是平衡的。如果有人能给我指明正确的方向,我将不胜感激

/**
* 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;
}

您应该首先将Mobile类拆分为Rod和Bob的不同子类。在下一步中,您可以为这两种类型定义不同的isBalanced()方法。Bob总是平衡的,对于Rod,你必须递归地分析左移动和右移动。如果遇到Bob,递归会自动停止。需要确定移动设备是否平衡的左移动设备或右移动设备的总重量也必须递归计算。

最新更新