Last active
May 31, 2020 15:25
-
-
Save chez-shanpu/df77ae44af0dc6968e887525073dc7db to your computer and use it in GitHub Desktop.
Bloom Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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