Bloom Filter
Last updated
Last updated
import java.util.BitSet;
public class BloomFilter {
// Number of bits
private static final int DEFAULT_SIZE = 1 << 25;
// Seeds for different hash functions, seed is prime number
private static final int[] seeds = {5, 7, 11, 13, 31, 37, 61};
// Bit Map
private BitSet bits = new BitSet(DEFAULT_SIZE);
private SimpleHash hashFunctions[] = new SimpleHash[seeds.length];
public BloomFilter() {
// Initialize Hash Functions for Bloom Filter
for (int i = 0; i < seeds.length; i++) {
hashFunctions[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]);
}
}
public void add(String key) {
for (SimpleHash function : hashFunctions) {
bits.set(function.hash(key), true);
}
}
public boolean contains(String key) {
boolean res = true;
for (SimpleHash function : hashFunctions) {
res = res && bits.get(function.hash(key));
}
return res;
}
class SimpleHash {
int capacity;
int seed;
public SimpleHash(int capacity, int seed) {
this.capacity = capacity;
this.seed = seed;
}
public int hash(String key) {
int res = 0;
for (int i = 0; i < key.length(); i++) {
res = res * seed + key.charAt(i);
}
return (capacity - 1) & res;
}
}
}