Skip to content

Create BloomFilter #3042

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.thealgorithms.datastructures.bloomfilter;


public class BloomFilter<T> {

private int numberOfHashFunctions;
private int [] bitArray;
private Hash<T>[] 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<T> hash : hashFunctions){
bitArray[hash.compute(key) % bitArray.length] = 1;
}
}

public boolean contains(T key) {
for (Hash<T> hash : hashFunctions){
if (bitArray[hash.compute(key) % bitArray.length] == 0){
return false;
}
}
return true;
}

private class Hash<T> {

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<word.length();i++){
number += word.charAt(i);
}
return number;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.thealgorithms.datastructures.bloomfilter;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;


public class BloomFilterTest {

@Test
public void test1(){
BloomFilter<Integer> 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<String> bloomFilter = new BloomFilter<>(4,20);
bloomFilter.insert("omar");
bloomFilter.insert("mahamid");

Assertions.assertTrue(bloomFilter.contains("omar"));
Assertions.assertTrue(bloomFilter.contains("mahamid"));
}
}