diff --git a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java new file mode 100644 index 00000000..ed77bb3c --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java @@ -0,0 +1,59 @@ +package com.thealgorithms.datastructures.bloomfilter; + + +public class BloomFilter { + + private int numberOfHashFunctions; + private int [] bitArray; + private Hash[] hashFunctions; + + public BloomFilter(int numberOfHashFunctions, int n) { + this.numberOfHashFunctions = numberOfHashFunctions; + hashFunctions = new Hash[numberOfHashFunctions]; + bitArray = new int[n]; + insertHash(); + } + + private void insertHash() { + for (int i = 0; i < numberOfHashFunctions; i++) { + hashFunctions[i] = new Hash(i); + } + } + + public void insert(T key) { + for (Hash hash : hashFunctions){ + bitArray[hash.compute(key) % bitArray.length] = 1; + } + } + + public boolean contains(T key) { + for (Hash hash : hashFunctions){ + if (bitArray[hash.compute(key) % bitArray.length] == 0){ + return false; + } + } + return true; + } + + private class Hash { + + int index; + + public Hash(int index){ + this.index = index; + } + + public int compute(T key){ + return index * asciiString(String.valueOf(key)); + } + + private int asciiString(String word){ + int number = 0; + for (int i=0;i bloomFilter = new BloomFilter<>(3,10); + bloomFilter.insert(3); + bloomFilter.insert(17); + + Assertions.assertTrue(bloomFilter.contains(3)); + Assertions.assertTrue(bloomFilter.contains(17)); + } + + @Test + public void test2(){ + BloomFilter bloomFilter = new BloomFilter<>(4,20); + bloomFilter.insert("omar"); + bloomFilter.insert("mahamid"); + + Assertions.assertTrue(bloomFilter.contains("omar")); + Assertions.assertTrue(bloomFilter.contains("mahamid")); + } +}