我正在尝试用递归算法来解决水手、猴子和椰子的问题。如果可以用给定值解决问题,我希望我的程序声明true或false。简而言之,问题是有一些水手被困在一个岛上,带着一只猴子和几个椰子。整个晚上,一个水手会醒来,把y个椰子分成几堆,剩下一个给猴子。然后水手掩埋其中一堆,并将另外两堆放回一起。下一个水手醒来,做同样的事情(创建s个偶数桩,其中一个留给猴子,掩埋其中一个桩,然后放回其他桩)。
我还知道2个水手需要7个椰子,3个水手需要79个椰子,4个水手需要1021个椰子。
我在基本情况下遇到了困难。如果我有一个例子,我有4个水手和81个椰子,我的程序会说这是可能的,因为4%81=1。但是,一旦第二个水手去排序这个例子中的椰子,就没有足够的东西要排序了。
如有任何帮助或建议,将不胜感激。非常感谢!
public class test2 {
public static void main(String[] args) {
int sailors=4, sailorsRemaining=sailors, coconuts=81;
testCoconuts(sailors, sailorsRemaining, coconuts);
}//end main method
public static boolean testCoconuts(int sailors, int sailorsRemaining, int coconutsRemaining){
int s = sailors;
int sr = sailorsRemaining;
int cr = coconutsRemaining;
if (cr%s==1 && sr==0) { //if there are enough coconuts to sort, but no sailors
System.out.println("false1");
return false;
}
else if (cr%s==1 && sr!=0) { //if there are enough coconuts and enough sailors to sort
System.out.print("true1");
return true;
}
if (cr%s!=1) { //if there are not enough coconuts to sort
System.out.println("false2");
return false;
}
else return testCoconuts(s, cr - ((cr-1)/s)-1, sr-1); //recursive step
}
}//end class发布于 2017-01-16 11:48:21
你的方法接受(水手,水手剩余,椰子计数),但你的返回方法发送(水手,椰子计数,水手剩余)。你调换了订单。尽管如此,它仍然没有修复它。我重写了if语句,现在它可以工作了,我想。我通过回答以下几点来做到这一点:
回答这两个问题,完成起来应该是轻而易举的。对我来说,调试是解决问题的关键。
https://stackoverflow.com/questions/41668700
复制相似问题