Net Core教程

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

 

这篇关于C#实现简单的布隆过滤器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!