Created
May 31, 2017 06:59
-
-
Save azuchi/e0ad6c06f911d9534ae47410dfe32677 to your computer and use it in GitHub Desktop.
簡易的なBloomFilterの実装
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 'murmurhash3' | |
| class BloomFilter | |
| SEED_BASE = 0xFBA4C795 | |
| attr_reader :bits | |
| attr_reader :hash_funcs | |
| attr_reader :tweak | |
| def initialize(n, k, tweak) | |
| @bits = Array.new(n, 0) # ビット列 | |
| @tweak = tweak # 乱数 | |
| @hash_funcs = k # ハッシュ関数の数 | |
| end | |
| # フィルタに要素を追加 | |
| def add(data) | |
| calc_index(data).each do |i| | |
| bits[i] = 1 | |
| end | |
| end | |
| # フィルタに要素が登録されているか確認 | |
| def contains?(data) | |
| calc_index(data).map{|i|bits[i]}.find{|i| i == 0}.nil? | |
| end | |
| private | |
| def calc_index(data) | |
| list = [] | |
| hash_funcs.times do |i| | |
| seed = (i * SEED_BASE + tweak) & 0xffffffff | |
| hash = MurmurHash3::V32.str_hash(data, seed) | |
| list << hash % bits.length | |
| end | |
| list | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment