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...)
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).
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With