1. 程式人生 > 其它 >C#實現簡單的布隆過濾器

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