Search code examples
javamethodsmode

Method for checking Mode


I have this method here, checking for the Mode (most frequent element) in an array. Although there is a twist I need to account for and i'm not sure how to go about doing this. For example: if my array is {1,2,2,3,3,5} .. I need to print out 'NaN' , because 2 and 3 both occur 2 times. Any help on how to add this is appreciated.

My code:

  public double mode() {
    double maxValue=0, maxCount=0;
    boolean flag=false;

    for (int i = 0; i < data.length; ++i) 
        {
            double count = 0;
                for (int j = 0; j < data.length; ++j) 
                    {
                        if (data[j]==(data[i])) ++count;
                    }
                if (count > maxCount)
                {
                        if(count>1)flag = true;
                        maxCount = count;
                        maxValue = data[i];
                }
        }
        if(flag)
        {
            return maxValue;
        }
        else return 0.0;
    } 

Solution

  • I suppose your current code is not exactly giving out the result you wanted.

    Here's a code snippet updated:

    public double mode() {
            // Sort array
            Arrays.sort(data);
    
            double maxValue = 0.0, maxCount = 0.0;
            for (int i = 0; i < data.length; ++i) {
    
                // Count number of elements with same value
                int count = 0;
                int index = i;  
                while (index < data.length) {
                    if (data[i] == data[index]) {
                        count++;
                        index++;
                    } else {
                        break;
                    }
                }
    
                if (count > maxCount) {
                    maxCount = count;
                    maxValue = data[i];
                } else if (count == maxCount) {
                    maxCount = count;
                    maxValue = 0.0;
                }
            }
    
            return maxValue;
        }
    

    Then, from the point where you call mode(), do the following:

    double m = mode();
    System.out.println(m == 0.0 ? "NaN" : m);