我对以下挑战有一个问题:
两个玩家(编号为1和2)正在玩一个有n块石头的游戏。玩家1总是先玩,两个玩家轮流移动。游戏规则如下:
在一次移动中,玩家可以从游戏板上移走2,3或5块石头。如果玩家不能移动,该玩家就会输掉比赛。给定棋子的数量,找到并在新的一行上打印获胜者的名字(即,第一或第二)。每个玩家都打得最好,这意味着如果存在一些更好的,获胜的棋,他们不会做出导致他们输掉比赛的棋。
(输出格式
在每个测试用例的新行上,如果第一个玩家获胜,则打印" first“;否则,打印”Second“。)
示例:
数量= 7,玩家= 1。
调用getWinner(7-5,-1)
数量= 2,玩家= -1
调用getWinner(2-2,1)
amount= 0,播放器=1
这个函数不应该在这里返回任何东西,因为它会中止搜索,但是编译器强制我添加一个return语句。
public static String getWinner(int amount, int player){
if (amount == 0 || amount == 1){
if (player == -1) {
return "First";
}
} else if (amount-5 >=0){
return getWinner(amount-5,-player);
} else if (amount-3 >=0) {
return getWinner (amount-3,-player);
} else if(amount-2 >= 0){
return getWinner (amount -2 , -player);
} else {
return "Second";
}
return "failure";
}
发布于 2016-08-29 00:04:41
代码没有任何意义,因为您实际上从来没有选择过任何东西,而是先做什么就做什么。此外,对于游戏的每一步,可能有些选择会让你松散,有些选择会让你获胜,所以你需要知道你想要什么。
你需要根据对手输的情况选择2、3或5。
private static boolean wins(int amount){
if (amount < 0 ) {
return true; // game already over, previous player lost
} else if ( amount <= 1){
return false; // you loose always
} else {
// we win if the opponent doesn't
return wins(amount-5) == false ||
wins(amount-3) == false ||
wins(amount-2) == false;
}
}
正如您所看到的,默认情况是这样做的,或者在递归之间。它会在第一次递归变为false时停止,否则结果将为true,否则为false。
发布于 2016-08-28 21:24:21
您的问题是,当第一个条件(amount == 0 || amount == 1
)为真时,并不总是返回(只返回if player==-1
),因此对于编译器而言,并非if
-else if
-...-else
语句的所有分支都返回值,这就是为什么您必须添加一条return语句作为方法的最后一条语句的原因。
您可以按如下方式重写逻辑以消除return "failure"
:
public static String getWinner(int amount, int player){
if (amount == 0 || amount == 1){
if (player == -1) {
return "First";
} else {
return "Second";
}
} else if (amount-5 >=0){
return getWinner(amount-5,-player);
} else if (amount-3 >=0) {
return getWinner (amount-3,-player);
} else { // you no longer need the else if(amount-2 >= 0) condition
// since it must be satisfied at this point
return getWinner (amount -2 , -player);
}
}
另一种选择:
public static String getWinner(int amount, int player){
if ((amount == 0 || amount == 1) && player == -1) {
return "First";
} else if (amount-5 >=0) {
return getWinner(amount-5,-player);
} else if (amount-3 >=0) {
return getWinner (amount-3,-player);
} else if(amount-2 >= 0) {
return getWinner (amount -2 , -player);
} else {
return "Second";
}
}
https://stackoverflow.com/questions/39191675
复制相似问题