Skip to content

Instantly share code, notes, and snippets.

@gauravat16
Last active April 18, 2020 19:32
Show Gist options
  • Save gauravat16/c1b97faf6cb17666d5da8e45c34ebc4c to your computer and use it in GitHub Desktop.
Save gauravat16/c1b97faf6cb17666d5da8e45c34ebc4c to your computer and use it in GitHub Desktop.
package bloomfilter;
import java.util.Arrays;
import java.util.BitSet;
public abstract class AbstractBloomFilter implements BloomFilter {
protected BitSet bitSet;
protected int expectedElements = -1;
protected double falsePosProbability = -1;
protected int optimumHashFunctions = -1;
public AbstractBloomFilter(int size) {
this.bitSet = new BitSet(size);
}
public AbstractBloomFilter(double falsePosProbability, int expectedElements) {
int size = (-1 * (expectedElements * log2(falsePosProbability) / (log2(2) * log2(2))));
int fnCount = ((size / expectedElements) * log2(2));
this.bitSet = new BitSet(size);
this.expectedElements = expectedElements;
this.falsePosProbability = falsePosProbability;
this.optimumHashFunctions = fnCount;
}
@Override
public void addData(String data) {
Arrays.stream(getHashedIndexForBitSet(data)).forEach(bitSet::set);
}
@Override
public boolean isPresent(String data) {
return Arrays.stream(getHashedIndexForBitSet(data)).allMatch(bitSet::get);
}
@Override
public String getInfo() {
return "\n BloomFilter :: \n\tsize :: " + bitSet.size() + "\n\tfalsePosProbability :: " + falsePosProbability
+ "\n\texpectedElements :: " + expectedElements
+ "\n\toptimumHashFunctions :: " + optimumHashFunctions + "\n";
}
abstract int[] getHashedIndexForBitSet(String data);
public static int log2(double f) {
return (int) Math.floor(Math.log(f) / Math.log(2.0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment