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++;
            }

 

posted @ 2021-08-12 16:21  可乐加冰-Mr-Wang  阅读(205)  评论(0编辑  收藏  举报