Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the most common occurrence in an array

Tags:

java

algorithm

Assume I have an array of doubles that looks like the following:

Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}

I need a function that can determine what the MAJORTY vote is in the array, in this case "10" because it is the number that appears the most often... And of course there is the situation when no majority exists (where they are equal), in that case I need to throw an exception...

Any clues? Aside from doing some really nasty looping on the array (for each index, determine how many exist with the same value, store a count in the array, and then scan the count array for the highest number and the value at that position is the winner, etc...)

like image 552
Shaitan00 Avatar asked Dec 05 '09 16:12

Shaitan00


People also ask

How do you find the most common value in an array?

Steps to find the most frequency value in a NumPy array:Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).

How do I find the most common number in an array Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.


2 Answers

Using a Map<Integer, Integer> should be simple as:

int mostFrequent(int... ary) {
    Map<Integer, Integer> m = new HashMap<Integer, Integer>();

    for (int a : ary) {
        Integer freq = m.get(a);
        m.put(a, (freq == null) ? 1 : freq + 1);
    }

    int max = -1;
    int mostFrequent = -1;

    for (Map.Entry<Integer, Integer> e : m.entrySet()) {
        if (e.getValue() > max) {
            mostFrequent = e.getKey();
            max = e.getValue();
        }
    }

    return mostFrequent;
}
like image 161
dfa Avatar answered Nov 04 '22 06:11

dfa


Your first problem is that you have an "array of doubles", because equality is problematic with floating point data (identical numerical values can be represented by different bit patters, among other things). If your doubles are in fact (as in the example) integers, use int instead. Otherweise, think long and hard about how you define what values are equal for the purpose of representing the same vote.

As for determining the majority vote, use a Map with the "vote id" as key and the number of votes as value - then in the end iterate through the map to find the maximal value.

like image 27
Michael Borgwardt Avatar answered Nov 04 '22 06:11

Michael Borgwardt