C#实现简单的布隆过滤器
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace UserCheckDemo { public class BloomFilter { public BitArray _bloomArray; public Int64 BloomArrayLength { get; } public Int64 BitIndexCount { get; } public Int64 _numberOfHashed; public BloomFilter(int BloomArrayLength, int bitIndexCount) { _bloomArray = new BitArray(BloomArrayLength); this.BloomArrayLength = BloomArrayLength; this.BitIndexCount = bitIndexCount; } public void Add(string str) { var hashCode = GetHashCode(str); Random random = new Random(hashCode); for (int i = 0; i < BitIndexCount; i++) { var ss = (int)(this.BloomArrayLength - 1); var c = random.Next(ss); _bloomArray[c] = true; } } public bool IsExist(string str) { var hashCode = GetHashCode(str); Random random = new Random(hashCode); for (int i = 0; i < BitIndexCount; i++) { var s = random.Next((int)(this.BloomArrayLength - 1)); if (!_bloomArray[s]) { return false; } } return true; } public int GetHashCode(object value) { return value.GetHashCode(); } /// <summary> /// 计算基本布隆过滤器散列的最佳数量 /// </summary> /// <param name="bitSize"></param> /// <param name="setSize"></param> /// <returns></returns> public int OptionalNumberHashes(int bitSize, int setSize) { return (int)Math.Ceiling((bitSize / setSize) * Math.Log(2.0)); } } }
BloomFilter bf = new BloomFilter(1000000, 3); int errorCount = 0; for (int i = 0; i < 100000; i++) { bf.Add($"key{i}"); } for (int i = 10000; i < 12000; i++) { if (bf.IsExist($"key{i}")) errorCount++; }
本文来自博客园,作者:可乐加冰-Mr-Wang,转载请注明原文链接:https://www.cnblogs.com/helloworld-wang/p/15133307.html