Created
November 30, 2011 20:59
-
-
Save xoebus/1410792 to your computer and use it in GitHub Desktop.
A Bloom Filter in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "zlib" | |
class BloomFilter | |
def initialize(size=100, hash_count=3) | |
raise(ArgumentError, "negative or zero buffer size") if size <= 0 | |
raise(ArgumentError, "negative or zero hash count") if hash_count <= 0 | |
@size = size | |
@hash_count = hash_count | |
@buffer = Array.new(size, false) | |
end | |
def insert(element) | |
hash(element).each { |i| @buffer[i] = true} | |
end | |
def maybe_include?(element) | |
hash(element).map { |i| @buffer[i] }.inject(:&) | |
end | |
private :hash | |
def hash(element) | |
hashes = [] | |
1.upto(@hash_count) do |i| | |
hashes << Zlib.crc32(element, i) | |
end | |
hashes.map { |h| h % @size } | |
end | |
end | |
b = BloomFilter.new(50, 5) | |
b.insert("hello") | |
puts b.maybe_include?("hello") # => true | |
puts b.maybe_include?("goodbye") # => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I realise the hashing is stupid but IDGAF.