-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmvn.h
59 lines (48 loc) · 1.32 KB
/
mvn.h
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
56
57
58
/*
* An implementation of Matias, Yossi, et al.'s O(log* n) sampling algorithm
* for categorical random variables. The original algorithm was specified in
* "Dynamic Generation of Discrete Random Variables".
*/
#ifndef MVN_H
#define MVN_H
#include <random>
#include <unordered_map>
#include <vector>
namespace std {
template<> struct hash<std::pair<uint64_t, uint64_t>> {
size_t operator()(const std::pair<uint64_t, uint64_t>& p) const;
};
};
class mvn {
private:
struct mvn_node {
uint64_t sum;
int value;
int level;
bool enqueued;
bool has_parent;
std::vector<mvn_node*> children;
uint64_t prev_sum;
uint64_t root_sum;
int parent_pos;
mvn_node();
};
using level_index_pair = std::pair<uint64_t, uint64_t>;
uint64_t level_count;
std::vector<uint64_t> level_totals;
std::unordered_map<level_index_pair, mvn_node*> nodes;
std::vector<mvn_node*> base_nodes;
std::vector<uint64_t> weights;
std::vector<uint64_t> roots;
uint64_t total_weight;
std::random_device rd;
std::mt19937_64 gen;
void construct_tree(const std::vector<uint64_t> &dist);
public:
mvn(const std::vector<uint64_t> &dist);
~mvn();
int sample();
void update(int idx, int value);
void delta_update(int idx, int delta);
};
#endif