| 19 | import java.util.*; |
| 20 | |
| 21 | public class Histogram<E> { |
| 22 | |
| 23 | private Map<E, HistogramEntry> map = new HashMap<E, HistogramEntry>(); |
| 24 | private float totalValue = 0; |
| 25 | private int totalCount = 0; |
| 26 | |
| 27 | public void add(E x) { |
| 28 | add(x, 1); |
| 29 | } |
| 30 | |
| 31 | public void add(E x, float value) { |
| 32 | HistogramEntry entry; |
| 33 | if (map.containsKey(x)) { |
| 34 | entry = map.get(x); |
| 35 | entry.value += value; |
| 36 | entry.count++; |
| 37 | } else { |
| 38 | entry = new HistogramEntry(); |
| 39 | entry.value = value; |
| 40 | entry.count = 1; |
| 41 | map.put(x, entry); |
| 42 | } |
| 43 | totalValue += value; |
| 44 | totalCount += 1; |
| 45 | } |
| 46 | |
| 47 | public Set<E> getKeys() { |
| 48 | return map.keySet(); |
| 49 | } |
| 50 | |
| 51 | public float getValue(E x) { |
| 52 | return map.get(x).value; |
| 53 | } |
| 54 | |
| 55 | public int getCount(E x) { |
| 56 | return map.get(x).count; |
| 57 | } |
| 58 | |
| 59 | public void add(Histogram<E> other) { |
| 60 | for (E x : other.getKeys()) { |
| 61 | add(x, other.getValue(x)); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | public Histogram<E> normalize() { |
| 66 | Histogram<E> normalized = new Histogram<E>(); |
| 67 | Set<E> keys = getKeys(); |
| 68 | for (E x : keys) { |
| 69 | normalized.add(x, getValue(x) / totalValue); |
| 70 | } |
| 71 | return normalized; |
| 72 | } |
| 73 | |
| 74 | public List<E> sortInverseByValue() { |
| 75 | List<Map.Entry<E, HistogramEntry>> list = new Vector<Map.Entry<E, HistogramEntry>>( |
| 76 | map.entrySet()); |
| 77 | |
| 78 | // Sort the list using an annonymous inner class implementing Comparator for |
nothing calls this directly
no outgoing calls
no test coverage detected