-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcounting_bf.h
90 lines (73 loc) · 1.7 KB
/
counting_bf.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifndef COUNTING_BF_H_
#define COUNTING_BF_H_
#include <random>
#include <string>
#include <vector>
namespace std {
string to_string(const string& str) {
return str;
}
} // namespace std
namespace {
// std::_Hash_impl::hash are implementation defined
template<class T = size_t>
class hasher{
public:
hasher() : Seed(std::mt19937{std::random_device{}()}()) {}
size_t operator()(T x) {
std::string str = std::to_string(x);
return std::_Hash_impl::hash(str.data(), std::size(str), Seed);
}
private:
size_t Seed;
};
} // namespace
template<class T>
class counting_bloom_filter{
public:
counting_bloom_filter(double failProbability, size_t n, size_t teta)
: Teta(teta) {
auto ln2 = std::log(2);
size_t m = std::ceil(-(n * std::log(failProbability) / ln2 / ln2));
size_t k;
if (Teta > 30) {
k = std::ceil(static_cast<double>(m) / n * (0.2037 * Teta + 0.9176));
} else {
k = std::ceil(static_cast<double>(m) / n * ln2);
}
Bits.resize(m);
Hashes.resize(k);
}
void add(const T& x) {
for (auto& hash : Hashes) {
++Bits[hash(x) % std::size(Bits)];
}
}
bool remove(const T& x) {
for (auto& hash : Hashes) {
if (Bits[hash(x) % std::size(Bits)] == 0) {
return false;
}
}
for (auto& hash : Hashes) {
--Bits[hash(x) % std::size(Bits)];
}
return true;
}
bool check(const T& x) {
for (auto& hash : Hashes) {
if (Bits[hash(x) % std::size(Bits)] < Teta) {
return false;
}
}
return true;
}
void clear() {
std::fill(begin(Bits), end(Bits), 0);
}
private:
size_t Teta;
std::vector<size_t> Bits;
std::vector<hasher<T>> Hashes;
};
#endif // COUNTING_BF_H_