package main
import (
"fmt"
"hash/fnv"
"math"
)
// BloomFilter 布隆过滤器结构
type BloomFilter struct {
size uint // 位数组大小
hashCount uint // 哈希函数数量
bitArray []bool // 位数组
hashFuncs []hashFunc // 哈希函数列表
}
// hashFunc 哈希函数类型
type hashFunc func([]byte) uint
// NewBloomFilter 创建一个新的布隆过滤器
func NewBloomFilter(size uint, hashCount uint) *BloomFilter {
bf := &BloomFilter{
size: size,
hashCount: hashCount,
bitArray: make([]bool, size),
hashFuncs: make([]hashFunc, hashCount),
}
// 初始化哈希函数
for i := uint(0); i < hashCount; i++ {
bf.hashFuncs[i] = createHashFunc(i)
}
return bf
}
// createHashFunc 创建哈希函数
func createHashFunc(seed uint) hashFunc {
return func(data []byte) uint {
h := fnv.New32a()
h.Write(data)
return uint(h.Sum32()) + seed
}
}
// Add 添加元素到布隆过滤器
func (bf *BloomFilter) Add(item []byte) {
for _, hashFunc := range bf.hashFuncs {
index := hashFunc(item) % bf.size
bf.bitArray[index] = true
}
}
// Contains 检查元素是否可能存在于布隆过滤器中
func (bf *BloomFilter) Contains(item []byte) bool {
for _, hashFunc := range bf.hashFuncs {
index := hashFunc(item) % bf.size
if !bf.bitArray[index] {
return false
}
}
return true
}
// OptimalHashCount 计算最优的哈希函数数量
func OptimalHashCount(size uint, expectedElements uint) uint {
return uint(math.Ceil(float64(size) / float64(expectedElements) * math.Log(2)))
}
// OptimalSize 计算最优的位数组大小
func OptimalSize(expectedElements uint, falsePositiveRate float64) uint {
return uint(math.Ceil(-float64(expectedElements) * math.Log(falsePositiveRate) / math.Pow(math.Log(2), 2)))
}
func main() {
// 预期元素数量和误报率
expectedElements := uint(1000)
falsePositiveRate := 0.01
// 计算最优的位数组大小和哈希函数数量
size := OptimalSize(expectedElements, falsePositiveRate)
hashCount := OptimalHashCount(size, expectedElements)
// 创建布隆过滤器
bf := NewBloomFilter(size, hashCount)
// 添加元素
bf.Add([]byte("hello"))
bf.Add([]byte("world"))
// 检查元素是否存在
fmt.Println(bf.Contains([]byte("hello"))) // true
fmt.Println(bf.Contains([]byte("world"))) // true
fmt.Println(bf.Contains([]byte("foo"))) // false (可能误报)
}
共有 0 - 布隆过滤器(Bloom Filter)