Arya Atighehchian
Arya Atighehchian

Reputation: 1

how do i get the mode of a 2d array

I was wondering how to get the mode of a 2d array in java. What are some different ways I could approach the problem? So far here is my code for the method. EDIT: Also, i forgot to mention that the array has to be positive and single digit numbers so numbers from 0-9 inclusive.

public static int getMostRepeatedNumber(int[][] array) {
    int theMode = 0;
    if(array.length < 0){
        return -1;
    }
    for(int row = 0; row <array.length;row++){
        for(int col = 0; col <array[0].length; col++){
            int temp = array[row][col];
        }
    }



    return theMode;
}

Upvotes: 0

Views: 1664

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

Since you are only dealing with integers from 0 through 9, the easiest approach is to build a frequency table and then scan for the largest value:

public static int getMostRepeatedNumber(int[][] array) {
    if(array == null){
        return -1;
    }
    // build frequency table
    int[] frequencies = new int[10]; // all zero
    for(int [] row : array){
        for(int val : row){
            frequencies[val]++;
        }
    }

    // scan for the largest value
    int largest = 0;
    int mode = -1;
    for (int i = 0; i < 10; ++i) {
        if (frequencies[i] > largest) {
            largest = frequencies[i];
            mode = i;
        }
    }

    return mode;
}

Upvotes: 1

Pham Trung
Pham Trung

Reputation: 11294

Because elements in array are all single digit (from 0 to 9), so we can count and store the frequency of each value easily using an array int[]freq with length 10.

int[]freq = new int[10];
for(int[] row : array){
   for(int val : row)
      freq[val]++;
}

int mode = 0;
for(int i = 1; i < 10; i++)
    if(freq[i] > freq[mode])
        mode = i;

return mode;

Upvotes: 3

Related Questions