tags:

views:

314

answers:

3

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?

A: 

A basic, albeit inefficient algorithm would be something like:

static int modal( int[] values ) {
    int modal = 0;
    int mfreq = 0;
    for( int i : values ) {
        // Is this value the most frequent we've found so far?
        int freq = 0;
        for( int j : values ) {
            if( j == i ) {
                freq++;
            }
        }
        if( freq > mfreq ) {
            modal = i;
            mfreq = freq;
    }
    return modal;
}

You could do a little better by pre-calculating frequencies for each value and storing them, perhaps in a map or similar, although this would still require looping through values, and would still necessitate another loop to determine which has the highest frequency.

Rob
+5  A: 

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;
}
Chadwick
You could use AtomicInteger instead of Integer values to reduce the number of objects allocations if the count is above 128.
Peter Lawrey
+2  A: 

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) } 
    }
}
Kevin Williams