about summary refs log tree commit diff stats
path: root/histogram.h
diff options
context:
space:
mode:
authorKelly Rauchenberger <fefferburbia@gmail.com>2019-02-28 20:12:45 -0500
committerKelly Rauchenberger <fefferburbia@gmail.com>2019-02-28 20:12:45 -0500
commit01fcbeb60da0bff33d5d9f5b870d444cc418a01d (patch)
treee506e532c02d08505d4328df37f4fac8c816e89f /histogram.h
parent1890eb5d4a496aea5e9114550081ca63bd280f3b (diff)
downloadrawr-ebooks-01fcbeb60da0bff33d5d9f5b870d444cc418a01d.tar.gz
rawr-ebooks-01fcbeb60da0bff33d5d9f5b870d444cc418a01d.tar.bz2
rawr-ebooks-01fcbeb60da0bff33d5d9f5b870d444cc418a01d.zip
Converted to C++ style randomization
The logic in rawr::randomSentence with the cuts might be slightly different now but who even knows what's going on there.
Diffstat (limited to 'histogram.h')
-rw-r--r--histogram.h53
1 files changed, 44 insertions, 9 deletions
diff --git a/histogram.h b/histogram.h index 76d8f1b..c7e051b 100644 --- a/histogram.h +++ b/histogram.h
@@ -3,18 +3,53 @@
3 3
4#include <map> 4#include <map>
5#include <string> 5#include <string>
6#include <random>
7#include <iostream>
6 8
7template <class T> 9template <class T>
8class histogram { 10class histogram {
9 public: 11public:
10 void add(const T& inst); 12
11 void compile(); 13 void add(const T& inst)
12 const T& next() const; 14 {
13 void print() const; 15 freqtable_[inst]++;
14 16 }
15 private: 17
16 std::map<T, int> freqtable; 18 void compile()
17 std::map<int, T> distribution; 19 {
20 distribution_.clear();
21
22 int max = 0;
23 for (auto& it : freqtable_)
24 {
25 max += it.second;
26 distribution_.emplace(max, it.first);
27 }
28
29 freqtable_.clear();
30 }
31
32 const T& next(std::mt19937& rng) const
33 {
34 int max = distribution_.rbegin()->first;
35 std::uniform_int_distribution<int> randDist(0, max - 1);
36 int r = randDist(rng);
37
38 return distribution_.upper_bound(r)->second;
39 }
40
41 void print() const
42 {
43 for (auto& freqpair : freqtable_)
44 {
45 std::cout << freqpair.first << ": " << freqpair.second << std::endl;
46 }
47 }
48
49private:
50
51 std::map<T, int> freqtable_;
52 std::map<int, T> distribution_;
18}; 53};
19 54
20#endif /* end of include guard: HISTOGRAM_H_24094D97 */ 55#endif /* end of include guard: HISTOGRAM_H_24094D97 */