dwwilson66
dwwilson66

Reputation: 7066

Counting instances of a value in an array

Homework. Dice Game. I've got an array that represents five rolls of a die. Consider: diceRoll[] = {6,3,3,4,5}. I would LIKE to create a SECOND array that has the counts of values from one to six contained in diceRoll[], (e.g., occurence[] = {0,0,2,1,1,1} for the diceRoll[] above.) but I fear I'm getting lost in nested loops and can't seem to figure out which value I ~should~ be returning. occurence[] is a global variable, and the intent is that the array will contain six values...the count of ones (at index [0]), twos (at [1]), threes (at [2]), etc.

So Far:

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

I cannot, however, get the occurence=occurence+1 to work. bad operand types for binary operator is my most common error. I suspect I need to increment occurence OUTSIDE one or both of the for loops, but I'm lost.

Guidance? or perhaps the one-line easy way to do this? d

Upvotes: 0

Views: 3432

Answers (1)

twain249
twain249

Reputation: 5706

The easiest way I have to do this is to create the second array in order so that occurrence[0] = # of 1's occurrence[1] = # of 2's and so on. Then this becomes a 1 loop method.

//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 
} 

EDIT:

Then to get the count for any particular value use occurrence[value-1]

Upvotes: 4

Related Questions