Quantcast
Viewing all articles
Browse latest Browse all 34

Bloom Filter in C#

Here’s a simple implementation of a Bloom Filter.

    public class BloomFilter
    {
        HashAlgorithm hash;
        int m, n, k;
        BitArray table;

        public BloomFilter(HashAlgorithm h, int size, float falsePositiveRate)
        {
            hash = h;
            double bits = -(size * Math.Log(falsePositiveRate)) / Math.Pow(Math.Log(2), 2);
            double hashes = -Math.Log(0.7) * bits / size;
            n = size;
            k = (int)hashes;
            m = (int)bits;
            table = new BitArray(m);
        }

        IEnumerable<int> Probe(byte[] input)
        {
            int chunks = hash.HashSize / 32;
            for (int i = 0; i < k; i++)
            {
                byte[] val = hash.ComputeHash(input);
                for (int j = 0; j < chunks && i < k; j++, i++)
                    yield return Math.Abs(BitConverter.ToInt32(val, j)) % m;
            }
        }

        public void PutValue(byte[] input)
        {
            foreach (int index in Probe(input))
                table.Set(index,true);
        }

        public bool Exists(byte[] input)
        {
            foreach (int index in Probe(input))
            {
                if (!table.Get(index)) return false;
            }
            return true;
        }

    }

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 34

Trending Articles