gpt4 book ai didi

java - 数组从下一个最大值开始遍历

转载 作者:行者123 更新时间:2023-12-02 02:49:08 25 4
gpt4 key购买 nike

我正在开发一个有 N 个玩家的简单游戏。假设N=5,那么玩家将是:

Player 1, Player 2, Player 3, Player 4, Player 5.

就像在游戏中一样,五分之一将成为获胜者。这就是获胜的逻辑。每个玩家都可以从以下数组中获得任意一个值,即数组中的随机值。

0、1、2、4、8、16

得分最高的玩家将成为获胜者。

对于示例案例,我生成了 0 到分数数组大小 (6) 之间的随机索引,并将其分配给每个玩家。

    int[] data = {0,1,2,4,8,16};
int[] samples = new int[5];

Random random = new Random();
for(int j=0;j<5;j++){
int value = random.nextInt(6);
samples[j] = data[value];
}

然后,我得到了这样的结果:

0 16 2 8 1

如果出现多个最高分,则首先获得最高分的获胜者。在上述情况下,玩家 2 获胜,得分为 16。

这是第一轮。

现在,我想为玩家 2(即玩家 3)分配随机生成的五个分数

这是第二个分数示例。

4 1 2 0 16

我想要的是分配这些分数,例如:

Player3 = 4
Player4 = 1
Player5 = 2
Player1 = 0
Player2 = 16

以上案例为第二轮。如何实现这一目标?如何像这样迭代数组,以便我可以找到 10 轮的获胜者。

如有任何建议,我们将不胜感激。

最佳答案

只要这只是练习而不是家庭作业,这里的方法就有效:

  int[] data = {0,1,2,4,8,16};
int[] samples = new int[5];

Random random = new Random();
int value;
int round = 3; // take in the number of rounds.
int[] wins = {0,0,0,0,0}; // we'll use this to store the player # of wins.
// Run the game for the specified number of rounds.
for(int i = 0; i < round; i++){
// Get 5 random numbers for each player.
for(int j=0;j<5;j++){
value = random.nextInt(6);
samples[j] = data[value];
}
// Set the current winner to junk values.
int max = Integer.MIN_VALUE;
int winner = 0;
// Run though the samples for the current round.
for(int j = 0; j < samples.length; j++){
// Print test of each players number.
System.out.println("Player" + (j + 1) + " Score " + samples[j]);
// Check in order which player won the round.
if(samples[j] > max){
max = samples[j];
winner = j;
}
}
// Increment the number of wins for the winner.
wins[winner]++;
System.out.println();
}
// Print test of round wins.
for(int i = 0; i < wins.length; i++){
System.out.println("Player" + (i+1) + " Wins " + wins[i]);
}
}

关于java - 数组从下一个最大值开始遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com