Any know how can I get the mode value from an array? For example, if I have a array with difference number, how can I use Java to search out which number is appears the most?
Completes in O(n) as opposed to O(n^2). Requires arrays of length > 0.
public static int getMode(int[] values) {
HashMap<Integer,Integer> freqs = new HashMap<Integer,Integer>();
for (int val : values) {
Integer freq = freqs.get(val);
freqs.put(val, (freq == null ? 1 : freq+1));
}
int mode = 0;
int maxFreq = 0;
for (Map.Entry<Integer,Integer> entry : freqs.entrySet()) {
int freq = entry.getValue();
if (freq > maxFreq) {
maxFreq = freq;
mode = entry.getKey();
}
}
return mode;
}
This is a little out there, and I don't know about it's performance, but if you were willing to try a little Groovy with your Java...
static int modal( ArrayList values ) {
use(Collections){
values.max{ values.frequency(it) }
}
}
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