File tree Expand file tree Collapse file tree 2 files changed +87
-0
lines changed
main/java/com/thealgorithms/datastructures/bloomfilter
test/java/com/thealgorithms/datastructures Expand file tree Collapse file tree 2 files changed +87
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments