Ahmed Beco
Ahmed Beco

Reputation: 55

A method to find the mode numbers

I have wrote a method to find the mode number of an array, length of the array is 10 so i have ten numbers in the array so the size is full . My question is if the mode is more than one number how i modify my code to display both numbers !

Ex if my array looks like this [1,1,1,2,2,2,3,5,6,8] the mode in this case is 1 and 2 . in my code it only prints the first mode it gets. so it will print mode is 1.

public static int arryMode (int [] randomList) {
    int maxValue = 0;
    int maxCount = 0;

    for (int i = 0; i < randomList.length; ++i) {
        int count = 0;

        for (int j = 0; j < randomList.length; ++j) {
             if (randomList[j] == randomList[i]) {
                 ++count;
             }
        }

        if (count > maxCount) {
            maxCount = count;
            maxValue = randomList[i];
        }
    }

    return maxValue;
}

Upvotes: 0

Views: 237

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109613

You will need to collect the several max values, and instead of replacing the maxValue when a greater max for count is found, you need to start with new max values. An extra case is needed for all those equal to the max value.

To not add a max value repeatedly look whether a new randomList[i] already is in the max values, and/or use a Set.

public static Set<Integer> arryMode(int[] randomList) {
    Set<Integer> maxValues = new LinkedHashSet<>(10);
    int maxCount = 0;
    for (int i = 0; i < randomList.length; ++i) {

        if (maxValues.contains(randomList[i])) { // Heuristic.
            continue;
        }

        int count = 0;
        for (int j = 0; j < randomList.length; ++j) {
            if (randomList[j] == randomList[i]) {
                ++count;
            }
        }
        if (count > maxCount) {
            maxCount = count;
            maxValues.clear();
            maxValues.add(randomList[i]);
        } else if (count == maxCount) {
            maxValues.add(randomList[i]);
        }
    }
    return maxValues;
}

With

for (int maxValue : maxValues) { ... }

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692081

You would use an ArrayList<Integer> to store all the values of the mode. An ArrayList is an object behaving as a resizable array. Each time you would find a new mode, if its count is equald to the previous max count, then you would add it to the list. If the count is bigger than the previous max count, then you would clear the list, and add the new mode to the list.

Read the Java tutorial on collections.

Upvotes: 0

Related Questions