Finding the mode of a 2D array

Tags: ,



I’m trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.

I’m trying to find a way that will iterate through the array and return the modal value. What I have so far is:

    int value = 0;
    int[] freq = new int[100];

    for (int row = 0; row < score.length; row++) {
        for (int col = 0; col < score[row].length; col++) {
            score[row][col] = value;
            freq[value]++;
        }
    }
    int largest = 0;
    int mode = -1;

    for (int i = 0; i < 100; i++) {
        if (freq[i] > largest)
        {
            largest = freq[i];
            mode = i;
        }
    }
    System.out.println("modal score is: " +mode);

Problem is that this is just returning the modal score as 0, which it isn’t.

Answer

You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.

But all you do is:

   int value = 0;
   .....
   score[row][col] = value;
   freq[value]++;`

firstly you are changing the score array,( which is a problem for you I guess…) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.

SOLUTION: in the first double for block you should do:

        value = score[row][col];
        freq[value]++;

so I think you mixed up the order of the line, it should be the other way around.



Source: stackoverflow