feat: basic bloom filter impl

This commit is contained in:
2026-04-27 00:41:40 +02:00
parent 6c8cee3ac0
commit 5810df32f5
5 changed files with 83 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
BasedOnStyle: LLVM
IndentWidth: 4
TabWidth: 4
UseTab: Never
ContinuationIndentWidth: 4
+1
View File
@@ -0,0 +1 @@
a.out
View File
+8
View File
@@ -0,0 +1,8 @@
# Dev Docs
I've scaffolded but it I feel it makes more sense to just have a one file impl first in some .cpp file
and take it from there. So off we go to top level main.cpp
There is an original paper but I'm reading off from wiki for now https://en.wikipedia.org/wiki/Bloom_filter
+69
View File
@@ -0,0 +1,69 @@
#include <cstdio>
#include <string>
#include <set>
/*
* Bloom filters
* - n bit array
* - k hash functions
* - add_elem:
* - get the set of {h_i(elem) mod n} and mark them 1
* - check elem:
* - x is elem
* - generate same positions set, if any are false this does not belong
* for sure
* - no guarantees on presence
*/
const int N = 1024;
const int K = 5;
std::vector<bool> bf(N);
int hash_i(int i, int x) {
switch (i) {
case 1:
return x; // h1(i) = i is perfectly ok, std::hash will do the same
case 2:
// here we need something better
// the | 1 makes it co-rime to N always
return std::hash<std::string>{}(std::to_string(x)) | 1;
default:
return hash_i(1, x) + i * hash_i(2, x);
}
}
void add(int elem){
for(int i = 1;i<=K;i++){
int hash = hash_i(i, elem) % N;
bf[hash] = 1;
}
}
bool missing(int elem){
for(int i = 1;i<=K;i++){
int hash = hash_i(i, elem) % N;
if(!bf[hash]) return true; // actually missing
}
return false; // may be present
}
int main() {
srand(time(nullptr));
std::set<int> actually_present{};
const int LIM = 500;
for(int i = 1; i< LIM;i++){
if(rand()&1){
actually_present.insert(i);
add(i);
}
}
int wrong = 0;
for(int i=1;i<LIM;i++){
bool true_missing = !actually_present.count(i);
bool bloom_missing = missing(i);
if( true_missing != bloom_missing ) wrong++;
}
std::printf("%d/%d incorrect\n", wrong, actually_present.size());
}