Question

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;
    } 
Was it helpful?

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);

OTHER TIPS

Seeing as you return 0.0 when you don't find a mode, how about using this ternary when you call the mode() function:

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

Or to put it in full if you prefer:

final double mode = this.mode();
if(mode == 0.0)
{
    System.out.println("NaN");
}
else
{
    System.out.println(mode);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top