Skip to content

Commit f272d8a

Browse files
authored
Add Bloom Filter (TheAlgorithms#3042)
1 parent 00c758a commit f272d8a

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.thealgorithms.datastructures.bloomfilter;
2+
3+
4+
public class BloomFilter<T> {
5+
6+
private int numberOfHashFunctions;
7+
private int [] bitArray;
8+
private Hash<T>[] hashFunctions;
9+
10+
public BloomFilter(int numberOfHashFunctions, int n) {
11+
this.numberOfHashFunctions = numberOfHashFunctions;
12+
hashFunctions = new Hash[numberOfHashFunctions];
13+
bitArray = new int[n];
14+
insertHash();
15+
}
16+
17+
private void insertHash() {
18+
for (int i = 0; i < numberOfHashFunctions; i++) {
19+
hashFunctions[i] = new Hash(i);
20+
}
21+
}
22+
23+
public void insert(T key) {
24+
for (Hash<T> hash : hashFunctions){
25+
bitArray[hash.compute(key) % bitArray.length] = 1;
26+
}
27+
}
28+
29+
public boolean contains(T key) {
30+
for (Hash<T> hash : hashFunctions){
31+
if (bitArray[hash.compute(key) % bitArray.length] == 0){
32+
return false;
33+
}
34+
}
35+
return true;
36+
}
37+
38+
private class Hash<T> {
39+
40+
int index;
41+
42+
public Hash(int index){
43+
this.index = index;
44+
}
45+
46+
public int compute(T key){
47+
return index * asciiString(String.valueOf(key));
48+
}
49+
50+
private int asciiString(String word){
51+
int number = 0;
52+
for (int i=0;i<word.length();i++){
53+
number += word.charAt(i);
54+
}
55+
return number;
56+
}
57+
}
58+
59+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.datastructures.bloomfilter;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
7+
public class BloomFilterTest {
8+
9+
@Test
10+
public void test1(){
11+
BloomFilter<Integer> bloomFilter = new BloomFilter<>(3,10);
12+
bloomFilter.insert(3);
13+
bloomFilter.insert(17);
14+
15+
Assertions.assertTrue(bloomFilter.contains(3));
16+
Assertions.assertTrue(bloomFilter.contains(17));
17+
}
18+
19+
@Test
20+
public void test2(){
21+
BloomFilter<String> bloomFilter = new BloomFilter<>(4,20);
22+
bloomFilter.insert("omar");
23+
bloomFilter.insert("mahamid");
24+
25+
Assertions.assertTrue(bloomFilter.contains("omar"));
26+
Assertions.assertTrue(bloomFilter.contains("mahamid"));
27+
}
28+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy