File tree Expand file tree Collapse file tree 4 files changed +78
-0
lines changed
Expand file tree Collapse file tree 4 files changed +78
-0
lines changed Original file line number Diff line number Diff line change @@ -7,6 +7,7 @@ codingcircle contains the examples from the YouTube Coding Cirle.
77So far, the following exercises have been covered:
88
99- [ Autocomplete] ( ./autocomplete/ ) – implements an autocomplete feature using a trie
10+ - [ Bloom filter] ( ./bloomfilter/ ) – implements a bloom filter
1011- [ Busfactor] ( ./busfactor/ ) – calculates the the maximum load of a bus based on events
1112- [ Clever max] ( ./clevermax/ ) – calculates the maximum of two numbers
1213- [ Cons, Car, Cdr & co.] ( ./cons ) – implements a cons cell and the corresponding functions
Original file line number Diff line number Diff line change 1+ package bloomfilter
2+
3+ import (
4+ "crypto/sha1"
5+ "strconv"
6+ )
7+
8+ type BloomFilter struct {
9+ bitArray []bool
10+ size int
11+ numHashes int
12+ }
13+
14+ func NewBloomFilter (size , numHashes int ) * BloomFilter {
15+ return & BloomFilter {
16+ bitArray : make ([]bool , size ),
17+ size : size ,
18+ numHashes : numHashes ,
19+ }
20+ }
21+
22+ func (bf * BloomFilter ) Add (value string ) {
23+ for i := 0 ; i < bf .numHashes ; i ++ {
24+ hash := sha1 .New ()
25+ hash .Write ([]byte (value + strconv .Itoa (i )))
26+ digest := hash .Sum (nil )
27+
28+ index := int (digest [0 ])<< 24 | int (digest [1 ])<< 16 | int (digest [2 ])<< 8 | int (digest [3 ])
29+ index = index % bf .size
30+ if index < 0 {
31+ index += bf .size
32+ }
33+
34+ bf .bitArray [index ] = true
35+ }
36+ }
37+
38+ func (bf * BloomFilter ) Contains (value string ) bool {
39+ for i := 0 ; i < bf .numHashes ; i ++ {
40+ hash := sha1 .New ()
41+ hash .Write ([]byte (value + strconv .Itoa (i )))
42+ digest := hash .Sum (nil )
43+
44+ index := int (digest [0 ])<< 24 | int (digest [1 ])<< 16 | int (digest [2 ])<< 8 | int (digest [3 ])
45+ index = index % bf .size
46+ if index < 0 {
47+ index += bf .size
48+ }
49+
50+ if ! bf .bitArray [index ] {
51+ return false
52+ }
53+ }
54+
55+ return true
56+ }
Original file line number Diff line number Diff line change 1+ package bloomfilter_test
2+
3+ import (
4+ "testing"
5+
6+ "github.com/stretchr/testify/assert"
7+ "github.com/thenativeweb/codingcircle/bloomfilter"
8+ )
9+
10+ func TestBloomFilter (t * testing.T ) {
11+ bf := bloomfilter .NewBloomFilter (512 , 5 )
12+
13+ bf .Add ("www.example.com" )
14+ bf .Add ("dangerous.example.com" )
15+
16+ assert .True (t , bf .Contains ("www.example.com" ))
17+ assert .True (t , bf .Contains ("dangerous.example.com" ))
18+ assert .False (t , bf .Contains ("www.thenativeweb.io" ))
19+ }
Original file line number Diff line number Diff line change 1+ // Package bloomfilter implements a bloom filter.
2+ package bloomfilter
You can’t perform that action at this time.
0 commit comments