C#实现简单的布隆过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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));
        }
    }
}

 

1
2
3
4
5
6
7
8
9
10
11
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 @   可乐加冰-Mr-Wang  阅读(207)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示