【问题标题】:Array Traverse from next to Max value数组从下一个最大值遍历
【发布时间】:2017-05-21 02:36:59
【问题描述】:

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

玩家 1、玩家 2、玩家 3、玩家 4、玩家 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 轮的获胜者。

任何建议,帮助表示赞赏。

【问题讨论】:

  • 播放器是定义参数的对象吗?
  • 这里,只是大小为 5 的简单数组。索引定义玩家,值定义得分

标签: java arrays


【解决方案1】:

只要这只是练习而不是家庭作业,这里是可行的:

  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]);
  }
}

【讨论】:

  • 我只是想找出问题背后的逻辑,我在这里找到了。谢谢
【解决方案2】:

也许这会有所帮助。从某个索引start 开始遍历samples 的所有元素:

  for (int j = 0; j < samples.length; j++) {
      int si = (start + j) % samples.length;
      System.out.println("Loop count: " + j + " looking at samples[" + si + "]");
  }

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 2013-11-06
    • 2020-04-02
    • 2021-08-30
    • 2019-05-15
    • 1970-01-01
    • 2022-01-07
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多