Search code examples
javamode

Finding the mode of an array


Ok so I am stuck once again here is what I have

public static int mode(int[][] arr) {
    List<Integer> list = new ArrayList<Integer>();
    List<Integer> Mode = new ArrayList<Integer>();
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            list.add(arr[i][j]); 
        }
    }
    for(int i = 0; i < list.size(); i ++) {
        Mode.add((Mode.indexOf(i)+1));
    }
    System.out.println(Mode);
    return 0;
}

What I am trying to do is in order to find the mathematical mode of this array what I intend to do is for every number I encounter in the array increment the corresponding index by 1 eventually ending up with a new array with "tally" marks in the corresponding indexes, I am not sure } am going about this in the right way I need a dynamic array I assume in order to reach any number that may be encountered so one that can grow to whatever size I need, if my code is complete gibberish feel free to criticize at will :)


Solution

  • Have you considered using a Map instead of a List? That way you can eliminate the ugly indexOf call, and just refer to each instance of the elements by their value, not by doing a linear search each time. Then, all you have to do is find the key with the highest value in your map.