-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbloomfilter.h
94 lines (79 loc) · 2.09 KB
/
bloomfilter.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
90
91
92
93
94
#ifndef BLOOMFILTER_H
#define BLOOMFILTER_H
#include "hash.h"
#include <iostream>
#include <time.h>
class BloomFilter
{
private:
/**
* k = the number of hashfunctions
* MAX_CAPACITY = the number of bits in the Bloom filter
* LOG_2_RANGE = the log (base 2) of MAX_CAPACITY
* hash_func_rands = the random byte to be appended to the key before hashing
* filter = the bloom filter (bit-array)
*/
unsigned k;
const unsigned MAX_CAPACITY = 1024;
const unsigned LOG_2_RANGE = 10;
char* hash_func_rands;
bool* filter;
public:
/**
* @brief Constructor to initialize the filter
*/
BloomFilter(unsigned k);
/**
* @brief Destructor to delete the bit array and hash-function random bytes
*/
~BloomFilter();
/**
* @brief Inserts the key into the Bloom filter
*
* @param key : the key of the element to be added
* @return ** void
*/
void insert(char* key);
/**
* @brief Checks if the key is present in the filter
*
* @param key : the key of the element whose presence is to be checked
* @return true : if the key exists
* @return false : if the key doesn't exist
*/
bool containsKey(char* key);
};
BloomFilter::BloomFilter(unsigned k)
{
this->k = k;
srand(time(NULL));
filter = new bool[MAX_CAPACITY];
std::fill(filter, filter + MAX_CAPACITY, false);
hash_func_rands = new char[k];
for(unsigned i=0;i<k;i++)
hash_func_rands[i] = rand() % 47;
}
BloomFilter::~BloomFilter()
{
delete[] filter;
delete[] hash_func_rands;
}
void BloomFilter::insert(char* key)
{
for(unsigned i=0;i<k;i++)
{
unsigned hash = get_hash(key, hash_func_rands[i], LOG_2_RANGE);
filter[hash] = true;
}
}
bool BloomFilter::containsKey(char* key)
{
for(unsigned i=0;i<k;i++)
{
unsigned hash = get_hash(key, hash_func_rands[i], LOG_2_RANGE);
if(!filter[hash])
return false;
}
return true;
}
#endif