题目
让我们玩!你必须返回哪位球员赢了!如果是平局退货Draw!。
例子:
rps('scissors','paper') // Player 1 won!
rps('scissors','rock') // Player 2 won!
rps('paper','paper') // Draw!
测试用例:
import static org.junit.Assert.*;
import org.junit.Test;
public class KataTest {
@Test
public void test1() {
System.out.println("Fixed Tests Player 1 won!");
assertEquals("Player 1 won!", Kata.rps("rock", "scissors"));
assertEquals("Player 1 won!", Kata.rps("scissors", "paper"));
assertEquals("Player 1 won!", Kata.rps("paper", "rock"));
}
@Test
public void test2() {
System.out.println("Fixed Tests Player 2 won!");
assertEquals("Player 2 won!", Kata.rps("scissors", "rock"));
assertEquals("Player 2 won!", Kata.rps("paper", "scissors"));
assertEquals("Player 2 won!", Kata.rps("rock", "paper"));
}
@Test
public void test3() {
System.out.println("Fixed Tests Draw!");
assertEquals("Draw!", Kata.rps("scissors", "scissors"));
assertEquals("Draw!", Kata.rps("paper", "paper"));
assertEquals("Draw!", Kata.rps("rock", "rock"));
}
}
解题
My笨方法:
public class Kata {
public static String rps(String p1, String p2) {
if ("rock".equals(p1) && "scissors".equals(p2)) {
return "Player 1 won!";
} else if ("scissors".equals(p1) && "paper".equals(p2)) {
return "Player 1 won!";
} else if ("paper".equals(p1) && "rock".equals(p2)) {
return "Player 1 won!";
} else if ("scissors".equals(p1) && "rock".equals(p2)) {
return "Player 2 won!";
} else if ("paper".equals(p1) && "scissors".equals(p2)) {
return "Player 2 won!";
} else if ("rock".equals(p1) && "paper".equals(p2)) {
return "Player 2 won!";
} else if ("scissors".equals(p1) && "scissors".equals(p2)) {
return "Draw!";
} else if ("paper".equals(p1) && "paper".equals(p2)) {
return "Draw!";
} else if ("rock".equals(p1) && "rock".equals(p2)) {
return "Draw!";
} else {
return null;
}
}
}
Other:
巨聪明的方法们
public class Kata {
public static String rps(String p1, String p2) {
if(p1 == p2) return "Draw!";
int p = (p1 + p2).equals("scissorspaper") || (p1 + p2).equals("rockscissors") || (p1 + p2).equals("paperrock") ? 1 : 2;
return "Player " + p + " won!";
}
}
public class Kata {
public static String rps(String p1, String p2) {
return p1.equals(p2) ? "Draw!" : "Player " + ("scissorspaper paperrock rockscissors".contains(p1+p2)?1:2) + " won!";
}
}
public class Kata {
public static String rps(String p1, String p2) {
if (p1 == p2) {
return "Draw!";
} else {
String rules = "rockpaperscissorsrock";
if (rules.contains(p1+p2)) {
return "Player 2 won!";
} else {
return "Player 1 won!";
}
}
}
}
后记
他人的方法真是非常有趣,值得借鉴。