Created
September 23, 2019 16:21
-
-
Save sat0yu/01efd33b8c72bd5628aa6913aa9e6be0 to your computer and use it in GitHub Desktop.
A BloomFilter implementation
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 ( | |
"bufio" | |
"crypto/md5" | |
"encoding/hex" | |
"fmt" | |
"math/big" | |
"os" | |
) | |
type HashFunc func(e string) int | |
type BloomFilter struct { | |
filter []bool | |
hashFuncs []HashFunc | |
} | |
func (b *BloomFilter) build(m, k int) { | |
b.filter = make([]bool, m) | |
for i := 0; i < k; i++ { | |
b.hashFuncs = append(b.hashFuncs, genHashFunc(m, i)) | |
} | |
} | |
func (b *BloomFilter) regist(e string) { | |
k := len(b.hashFuncs) | |
for i := 0; i < k; i++ { | |
idx := b.hashFuncs[i](e) | |
b.filter[idx] = true | |
} | |
} | |
func (b *BloomFilter) check(e string) bool { | |
k := len(b.hashFuncs) | |
var result = true | |
for i := 0; i < k; i++ { | |
idx := b.hashFuncs[i](e) | |
if !b.filter[idx] { | |
result = false | |
} | |
} | |
return result | |
} | |
func genHashFunc(m, i int) HashFunc { | |
return func(e string) int { | |
bi := big.NewInt(0) | |
h := md5.New() | |
h.Write([]byte(fmt.Sprintf("%d%s", i, e))) | |
hexstr := hex.EncodeToString(h.Sum(nil)) | |
bi.SetString(hexstr, 16) | |
mo := bi.Mod(bi, big.NewInt(int64(m))) | |
return int(mo.Int64()) | |
} | |
} | |
func main() { | |
M := 256 | |
K := 16 | |
bf := BloomFilter{} | |
bf.build(M, K) | |
sc := bufio.NewScanner(os.Stdin) | |
for { | |
fmt.Printf("(Enter exit to finish registration)\n") | |
fmt.Printf("add > ") | |
sc.Scan() | |
in := sc.Text() | |
if in == "exit" { | |
break | |
} | |
bf.regist(in) | |
} | |
for { | |
fmt.Printf("(Enter exit to exit)\n") | |
fmt.Printf("check > ") | |
sc.Scan() | |
in := sc.Text() | |
if in == "exit" { | |
break | |
} | |
if bf.check(in) { | |
fmt.Println("Hit") | |
} else { | |
fmt.Println("Miss") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment