计算数组中的重复值

Counting repeated values in an array

我正在创建一个玩家掷五次骰子的游戏。结果记录在数组中。

private final int diceRolls = 5;
private int[] results = new int[diceRolls];

private void game() {
    Random randomNumber = new Random();
    for(int i=0; i<diceRolls; i++) {
        results[i] = randomNumber.nextInt(6) + 1;
    }
    Arrays.sort(results);
}

我正在实施一个计分系统,如果玩家掷出 3 个相同的数字,他将获得 10 分(即 1、1、1、4、5)。如果他掷出一个数字的 3 个和另一个数字的 2 个,他得 15 分。 (即 1、1、1、2、2)我该怎么做?

  • 骰子只有 6 个数字,您可以做的一件事就是搜索每个数字并做出决定。

直接搜索

for(int i=0;i<6;i++){
   int count=0;
   for(int j=0;j<dicecount;j++){
       //check each array element with i+1

   }
}
  • 维护一个Java映射数据结构来映射每个数字与计数值

地图实现

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(key, map.get(key) + 1);

Exbury 指出的第一个解决方案可能会起作用,但第二个更优化。

private void game() {
    Random randomNumber = new Random();
    for(int i=0; i<diceRolls; i++) {
        results[i] = randomNumber.nextInt(6) + 1;
    }
    Arrays.sort(results);
}

private int scoreCalc(int [] results)
{
  int score=0;
  for(int i = 0; i < 7; i++)
  {
    int repeated=0;
    for(int j = 0; j < results.length; j++)
    {
      if(results[j] == i)
      {
        repeated++;
      }
    }
    score += countPoints(repeated);
  }
}
private int countPoints(int repetitions){
//here goes the scoring system
}

此代码验证数字是否与前例相同。在您对数组结果进行排序后,它会遵循您的代码。

int count1 = 1;
int count2 = 1;
boolean sameThanBefore= false;

for (int = 1; i < diceRolls; i++) {
    if (results[i] == results[i-1]) {
        if (sameThanBefore && count1 < 2) {
            count1++;
            sameThanBefore = true;
        } else if (sameThanBefore) {
            count2++;
            sameThanBefore = true;
        }
    } else
        sameThanBefore = false;
}

if ((count1 == 3 && count2 == 2) || (count1 == 2 && count2 == 3))
    score = 15;
else if (count1 == 3 || count2 == 3)
    score = 10;