Find the mode (most frequent value in an array) using a simple for loop?

前端 未结 4 717
栀梦
栀梦 2020-12-20 10:30

How do I find the mode (most frequent value in an array) using a simple for loop?

The code compiles with a wrong output.

Here is what I have:



        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 11:12

    You should check the number of occurances of every element in your array. You can do it by comparing every element of array with herself and others via 2 inner for loops.

    Remember, if the array is not sorted and contains more then 1 modal value (thus repeating number of occurances) this will return the first one. It maybe wise to order the array first by Arrays.sort(array) so that you can pick the smallest or biggest modal value.

    public static int modeOfArray(int[] array){
        int mode;     
        int maxOccurance = 0;
    
        for(int i=0; i maxOccurance){
                maxOccurance = occuranceOfThisValue;
                mode = array[i];
            }
        }
        return mode;
    }
    

提交回复
热议问题