public class BloomFilter
{
public BitArray _BloomArray;
public Int64 BloomArryLength { get; }
public Int64 BitIndexCount { get; }
/// <summary>
/// 初始化
/// </summary>
/// <param name="BloomArryLength">布隆数组的大小</param>
/// <param name="bitIndexCount">hash次数</param>
public BloomFilter(int BloomArryLength, int bitIndexCount)
{
_BloomArray = new BitArray(BloomArryLength);
this.BloomArryLength = BloomArryLength;
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 c = random.Next((int)(this.BloomArryLength - 1));
_BloomArray[c] = true;
}
}
public bool isExist(string str)
{
var hashCode = GetHashCode(str);
Random random = new Random(hashCode);
for (int i = 0; i < BitIndexCount; i++)
{
if (!_BloomArray[random.Next((int)(this.BloomArryLength - 1))])
{
return false;
}
}
return true;
}
public int GetHashCode(object value)
{
return value.GetHashCode();
}
}
客户端
BloomFilter bf = new BloomFilter(1000000, 3);
for (int i = 0; i < 100000; i++)
{
bf.Add(i.ToString());
}
int errorCount = 0;
for (int i = 100000; i < 110000; i++)
{
if (bf.isExist(i.ToString()))
{
errorCount++;
}
}
转:https://www.cnblogs.com/yueyue184/p/10037587.html