计算数组中值的实例

时间:2012-03-20 00:27:39

标签: java arrays counting

作业。骰子游戏。我有一个代表五个模具的阵列。考虑: diceRoll[] = {6,3,3,4,5}。我想创建一个SECOND数组,其diceRoll[]中包含的值从1到6,(例如,occurence[] = {0,0,2,1,1,1}上面的diceRoll[]。但我担心我是迷失在嵌套循环中,似乎无法弄清楚我应该返回哪个值。 occurence[]是一个全局变量,其意图是数组将包含六个值...一个(在索引[0]处),两个(在[1]处),三个(在[2]处)的计数)等等。

到目前为止:

 for(i=1;i<7;i++)   /* die values 1 - 6
    {
       for(j=0;j<diceRoll.length;j++)  /* number of dice
       {
          if (diceRoll[j] == i)  /* increment occurences when die[j] equals 1, then 2, etc.
             occurence = occurence + 1;
       }
    }
    return occurence;
    }

然而,我不能让occurence = occurence + 1起作用。 bad operand types for binary operator是我最常见的错误。我怀疑我需要增加occurence OUTSIDE一个或两个for循环,但我迷路了。

指导?或者也许一线简单的方法来做到这一点? d

1 个答案:

答案 0 :(得分:4)

我必须这样做的最简单方法是按顺序创建第二个数组 occurrence [0] = 1的发生次数[1] = 2的#,依此类推。然后这成为一个循环方法。

//method to return number of occurrences of the numbers in diceRolls
int[] countOccurrences(int[] diceRolls) {
    int occurrence[] = new int[6]; //to hold the counts

    for(int i = 0; i < diceRolls.length; i++) { //Loop over the dice rolls array
       int value = diceRolls[i]; //Get the value of the next roll
       occurence[value]++; //Increment the value in the count array this is equivalent to occurrence[value] = occurrence[value] + 1;
       //occurrence[diceRolls[i]]++; I broke this into two lines for explanation purposes
    }

    return occurrence; //return the counts 
} 

编辑:

然后使用occurrence[value-1]

获取任何特定值的计数