布隆过滤器(c#简单实现)

 public class BloomFilter
    {
        public BitArray _BloomArray;
        public Int64 BloomArryLength { get; }
        public Int64 BitIndexCount { get; }

        /// 
        /// 初始化
        /// 
        /// 布隆数组的大小
        /// hash次数
        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

你可能感兴趣的:(布隆过滤器(c#简单实现))