Don Lester
Don Lester

Reputation: 37

How do I write a method to calculate the mode of an array?

I'm trying to write a method to calculate the mode of an array. I'm trying to write it with only two arrays. For some reason, the output I get is the size of the array --> 100. So far this is what I have:

public static int mode(int[ ] grades) {
  int mode[ ] = new int [101];
  int value = 0;

  for (int i = 0; i < value; i++)
    mode[grades[ i ] ]++;  //this part really confuses me and I don't know how to interpret this.
                           //can someone please explain this to me too.  I know this is the only...
  int max = 0;             //...way to get it with 2 arrays.

  for(int i = 0; i < 101; i++) {
    max = mode[ i ];
    value = i;
  }

  return value;
}

Upvotes: 1

Views: 226

Answers (1)

Steve P.
Steve P.

Reputation: 14709

grades can be in the range [0,100], which is 101 numbers (hence the size of 101).

for (int i = 0; i < value; i++)
    mode[grades[i]]++;

grades[i] gets the number at slot i. Let's say that's 85. This give us: mode[85]++, which increments the number of times we've seen the grade 85.

After this is complete, we iterate through mode and see which slot has the highest value, this value cooresponds to the mode, since mode simply keeps track of the number of times we encounter each score.

However, the second part is incorrect, you only want to update max, value if the current element is > max, ie:

int max = 0;           
for(int i = 0; i< 101; i++)
{
     if (mode[i] > max)
     {
         max = mode[i];
         value = i;
     }
}

Upvotes: 1

Related Questions