Skip to content

Instantly share code, notes, and snippets.

@nmische
Last active December 23, 2015 05:09
Show Gist options
  • Save nmische/6585475 to your computer and use it in GitHub Desktop.
Save nmische/6585475 to your computer and use it in GitHub Desktop.
Get the three most frequent numbers in a list.
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
public class numbers {
public static void main(String[] args) {
class ValueComparator implements Comparator<Integer> {
Map<Integer, Integer> base;
public ValueComparator(Map<Integer, Integer> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(Integer a, Integer b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
List<Integer> numbers = Arrays.asList(1,2,3,4,1,6,7,3,4,7,7,8,9,1,2,1,3,3,3,3,3,3,3);
HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();
ValueComparator vc = new ValueComparator(counts);
TreeMap<Integer,Integer> sortedCounts = new TreeMap<Integer,Integer>(vc);
for (Integer i: numbers) {
if (counts.get(i) == null) {
counts.put(i, 1);
} else {
counts.put(i, counts.get(i) + 1);
}
}
sortedCounts.putAll(counts);
int x = 0;
Iterator<Map.Entry<Integer,Integer>> sortedCountsIterator = sortedCounts.entrySet().iterator();
while( sortedCountsIterator.hasNext() && x < 3 ){
System.out.println(sortedCountsIterator.next());
x += 1;
}
}
}
x = [1,2,3,4,1,6,7,3,4,7,7,8,9,1,2,1,3,3,3,3,3,3,3]
x.inject({}) { |counts, x| counts[x] = 0 unless counts[x]; counts[x] += 1; counts }.sort_by{ |key,val| val }.reverse.first(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment