使用Java编写以下程序:
假设Player1有7个骰子,而Player2有5个骰子(所有12个骰子都是标准1到6个骰子且公平)。两名玩家掷出骰子并比较各自的总和(即玩家1投出1,3,5,2,6,1,1 = 19而玩家2投出2,1,4,6,3 = 16)。如果玩家1的总和高于玩家2,则玩家1赢得比赛,否则玩家2获胜。如果所有2,176,782,336个组合都滚动,那么Player1将赢得几场比赛? Player2将赢得几场比赛?多少场比赛将导致平局? (注意:仅需打印回答三个问题的总数)
卡住的部分是如何保证没有重复的卷?
谢谢。
import java.util.Random;
public class KDice {
public static void main(String[] args) {
Random random = new Random();
long playerOneWins = 0, playerTwoWins = 0, ties = 0;
int playerOneSum, playerTwoSum;
//for long number use L as suffix
for (long i = 0; i < 2176782336L; i++) {
//roll dice for player 1
playerOneSum = rollDice(random, 7);
//roll dice for player 2
playerTwoSum = rollDice(random, 5);
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
//after all the round done, display stats
System.out.println("Player 1 win: " + playerOneWins);
System.out.println("Player 2 win: " + playerTwoWins);
System.out.println("Ties: " + ties);
}
public static int rollDice(Random random, int count) {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += generateRandomNumber(random);
}
return sum;
}
public static int generateRandomNumber(Random random) {
return random.nextInt(6) + 1; //return number between 1 to 6
}
}
最佳答案
为了模拟12个骰子的每个可能掷骰,我使用12个嵌套的for循环,以便可以产生每个可能的掷骰。
我用以下循环替换了随机掷骰子:
int[] dice = new int[12];
for (dice[0] = 1; dice[0] <= 6; dice[0]++) {
System.out.println("dice[0] = " + dice[0]);
for (dice[1] = 1; dice[1] <= 6; dice[1]++) {
System.out.println("dice[1] = " + dice[1]);
for (dice[2] = 1; dice[2] <= 6; dice[2]++) {
System.out.println("dice[2] = " + dice[2]);
for (dice[3] = 1; dice[3] <= 6; dice[3]++) {
for (dice[4] = 1; dice[4] <= 6; dice[4]++) {
for (dice[5] = 1; dice[5] <= 6; dice[5]++) {
for (dice[6] = 1; dice[6] <= 6; dice[6]++) {
for (dice[7] = 1; dice[7] <= 6; dice[7]++) {
for (dice[8] = 1; dice[8] <= 6; dice[8]++) {
for (dice[9] = 1; dice[9] <= 6; dice[9]++) {
for (dice[10] = 1; dice[10] <= 6; dice[10]++) {
for (dice[11] = 1; dice[11] <= 6; dice[11]++) {
playerOneSum = dice[0] + dice[1] + dice[2] + dice[3] + dice[4] + dice[5] + dice[6];
playerTwoSum = dice[7] + dice[8] + dice[9] + dice[10] + dice[11];
//find who won
if (playerOneSum == playerTwoSum) {
ties++;
} else if (playerOneSum > playerTwoSum) {
playerOneWins++;
} else {
playerTwoWins++;
}
}
}
}
}
}
}
}
}
}
}
}
}
大约花了三到四分钟。我放入了println,以免我太急躁。结果是:
Player 1 win: 1877280394
Player 2 win: 225654001
Ties: 73847941