about summary refs log tree commit diff stats
path: root/histogram.h
blob: c7e051badf41e75840dd90f40b4ea1a35f014709 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef HISTOGRAM_H_24094D97
#define HISTOGRAM_H_24094D97

#include <map>
#include <string>
#include <random>
#include <iostream>

template <class T>
class histogram {
public:

  void add(const T& inst)
  {
    freqtable_[inst]++;
  }

  void compile()
  {
    distribution_.clear();

    int max = 0;
    for (auto& it : freqtable_)
    {
      max += it.second;
      distribution_.emplace(max, it.first);
    }

    freqtable_.clear();
  }

  const T& next(std::mt19937& rng) const
  {
    int max = distribution_.rbegin()->first;
    std::uniform_int_distribution<int> randDist(0, max - 1);
    int r = randDist(rng);

    return distribution_.upper_bound(r)->second;
  }

  void print() const
  {
    for (auto& freqpair : freqtable_)
    {
      std::cout << freqpair.first << ": " << freqpair.second << std::endl;
    }
  }

private:

  std::map<T, int> freqtable_;
  std::map<int, T> distribution_;
};

#endif /* end of include guard: HISTOGRAM_H_24094D97 */