-
-
Save MaherSaif/1b7b39dfac67fcf7defc1d276a07bcc4 to your computer and use it in GitHub Desktop.
Simple fuzzy index with left weight
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
class FuzzyIndex | |
def initialize | |
@index = Hash.new { |h, k| h[k] = Set.new } | |
end | |
def []=(key, value) | |
trigrams(key).each { @index[it] << [key, value] } | |
end | |
def [](query) | |
results = {} | |
trigrams(query).each do |trigram| | |
@index[trigram].each do |pair| | |
results[pair] ||= 0 | |
results[pair] += 1 | |
end | |
end | |
results | |
.map { |(k, v), score| [score.to_f / k.length, [k, v]] } | |
.sort_by { |(weight, pair)| -weight } | |
.take(10) | |
end | |
private | |
def trigrams(word) | |
padded_normalized_word = "■■#{word.downcase}" | |
(0..padded_normalized_word.length - 3).map do |index| | |
padded_normalized_word[index, 3] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment