Last active
December 20, 2015 02:49
-
-
Save newtonapple/6059061 to your computer and use it in GitHub Desktop.
This file contains 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
class Simhash | |
attr_reader :weights, :bits_length, :bitmasks | |
def initialize(bits_length=64) | |
@bits_length = bits_length | |
@weights = Array.new(@bits_length, 0.0) | |
@bitmasks = Array.new(@bits_length) | |
(0...@bits_length).each do |i| | |
@bitmasks[i] = (1 << i) | |
end | |
end | |
def update(hashes) | |
hashes.each {|h| update_hash h } | |
end | |
def update_hash(hash, weight=1.0) | |
@bitmasks.each_with_index do |mask, i| | |
@weights[i] += (hash & mask).zero? ? -weight : weight | |
end | |
end | |
def digest(hashes=[]) | |
update(hashes) | |
hash = 0 | |
@weights.each_with_index do |w, i| | |
if w >= 0 | |
hash |= @bitmasks[i] | |
end | |
end | |
hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment