0
我試圖通過遞歸算法解決水手,猴子和椰子問題。如果可以用給出的值解決問題,我希望我的程序表明真或假。總之,問題是有一些水手滯留在一個島上,有一隻猴子和椰子。整個晚上,一名水手會醒來,拿起椰子,分成幾堆,一隻椰子留給猴子。然後,水手將其中一個樁埋起來,並將另外兩個樁放回原處。下一個水手醒來,並且做同樣的事情(甚至爲一隻猴子留下一隻猴子,埋入其中一隻樁,並放回其他樁)。遞歸布爾方法的難點
我也知道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
我不明白爲什麼第一個水手會有1堆埋,然後有2堆合併。我以爲那是假設成堆的。 –
猴子得到1個椰子或1堆嗎? –
我建議使用調試器或添加'System.out.println()'語句來調試你的代碼。 –