Search code examples
javastringmode

How to determine if there isn't a mode in an array in java?


I have already wrote code that finds the mode (value that occurs the most often) in an array. If there is a mode (or multiple modes) in the array, the program works fine. But if there isn't a mode, my code prints out the whole array. I just want it to print "None" if there isn't a mode.

Here is my method code for finding the mode:

public static String mode(int [] a) {
    String m = "None";
    int k = 0;
    int n = 0;
    for (int i = 0; i < a.length; i++) {
        n = 1;
        for (int j = i; j < a.length; j++) {
            if (a[i] == a[j]) {
                n = n+1;
            }
        }
        if (n > k) {
            m = "" + a[i];
            k = n;
        }
        else if (k == n) {
            m = m + ", " + a[i];
        }
    }
    return m;
}   

Here is my main method code:

System.out.println("Mode: " + mode(a));

Solution

  • From your code and your explanation I assume that mode is "the most common element that occurs at least twice". What your code is missing in this case is the "at least twice" part. Your code currently just finds all the elements that occur most frequently, and obviously for an array where no element occurs at least twice returning the whole array would be correct.

    To fix it, change your last line from:

    return m;
    

    to

    if (k == 2) {
        return "None";
    }
    return m;
    

    Note that I compare k with 2, and not with 1. This is because of another issue in your code, caused by the fact that you initialize n to 1, and then increment it by the number of elements that are equal to the i-th element, including the i-th element. So if the element occurs once, n will be equal to 2, not 1, and, correspondingly, so will k. So to make code cleaner, you can either initialize n = 0, or start your inner loop from i+1 instead of starting it with i. In either of these cases change the constant in the snipped I provided above to 1.