Skip to content

Commit

Permalink
feat: Add new example.
Browse files Browse the repository at this point in the history
  • Loading branch information
goloroden committed Nov 10, 2024
1 parent 3a0f6c0 commit ebf3f32
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ codingcircle contains the examples from the YouTube Coding Cirle.
So far, the following exercises have been covered:

- [Autocomplete](./autocomplete/) – implements an autocomplete feature using a trie
- [Bloom filter](./bloomfilter/) – implements a bloom filter
- [Busfactor](./busfactor/) – calculates the the maximum load of a bus based on events
- [Clever max](./clevermax/) – calculates the maximum of two numbers
- [Cons, Car, Cdr & co.](./cons) – implements a cons cell and the corresponding functions
Expand Down
56 changes: 56 additions & 0 deletions bloomfilter/bloomfilter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package bloomfilter

import (
"crypto/sha1"
"strconv"
)

type BloomFilter struct {
bitArray []bool
size int
numHashes int
}

func NewBloomFilter(size, numHashes int) *BloomFilter {
return &BloomFilter{
bitArray: make([]bool, size),
size: size,
numHashes: numHashes,
}
}

func (bf *BloomFilter) Add(value string) {
for i := 0; i < bf.numHashes; i++ {
hash := sha1.New()
hash.Write([]byte(value + strconv.Itoa(i)))
digest := hash.Sum(nil)

index := int(digest[0])<<24 | int(digest[1])<<16 | int(digest[2])<<8 | int(digest[3])
index = index % bf.size
if index < 0 {
index += bf.size
}

bf.bitArray[index] = true
}
}

func (bf *BloomFilter) Contains(value string) bool {
for i := 0; i < bf.numHashes; i++ {
hash := sha1.New()
hash.Write([]byte(value + strconv.Itoa(i)))
digest := hash.Sum(nil)

index := int(digest[0])<<24 | int(digest[1])<<16 | int(digest[2])<<8 | int(digest[3])
index = index % bf.size
if index < 0 {
index += bf.size
}

if !bf.bitArray[index] {
return false
}
}

return true
}
19 changes: 19 additions & 0 deletions bloomfilter/bloomfilter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package bloomfilter_test

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/thenativeweb/codingcircle/bloomfilter"
)

func TestBloomFilter(t *testing.T) {
bf := bloomfilter.NewBloomFilter(512, 5)

bf.Add("www.example.com")
bf.Add("dangerous.example.com")

assert.True(t, bf.Contains("www.example.com"))
assert.True(t, bf.Contains("dangerous.example.com"))
assert.False(t, bf.Contains("www.thenativeweb.io"))
}
2 changes: 2 additions & 0 deletions bloomfilter/documentation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package bloomfilter implements a bloom filter.
package bloomfilter

0 comments on commit ebf3f32

Please sign in to comment.