Skip to content

Instantly share code, notes, and snippets.

@chez-shanpu
Last active May 31, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chez-shanpu/df77ae44af0dc6968e887525073dc7db to your computer and use it in GitHub Desktop.
Save chez-shanpu/df77ae44af0dc6968e887525073dc7db to your computer and use it in GitHub Desktop.
Bloom Filter
package main
import "fmt"
type bloomFilter struct {
bits uint
hashFunctions []hashFunction
}
type hashFunction struct {
descriptor int
}
func (b *bloomFilter) add(val int) {
for _, v := range b.hashFunctions {
b.bits |= 1 << v.calc(val)
}
}
func (b *bloomFilter) contains(val int) bool {
for _, v := range b.hashFunctions {
if b.bits&1<<v.calc(val) == 0 {
return false
}
}
return true
}
func (h *hashFunction) calc(val int) int {
return val % h.descriptor
}
func main() {
h1 := hashFunction{descriptor: 5}
h2 := hashFunction{descriptor: 7}
h3 := hashFunction{descriptor: 23}
b := bloomFilter{
bits: 0,
hashFunctions: []hashFunction{h1, h2, h3},
}
b.add(3)
b.add(10)
b.add(25)
fmt.Printf("%b\n", b.bits)
fmt.Println(b.contains(3))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment