-
-
Save chinthakagodawita/6204452 to your computer and use it in GitHub Desktop.
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 'rubygems' | |
require 'redis' | |
class RedisTrie | |
TERMINAL = '+' | |
def initialize(prefix) | |
@prefix = prefix | |
@r = Redis.new | |
end | |
def add_word(word) | |
w = word.gsub(/[^a-zA-Z0-9_-]/, '') | |
key = "#{@prefix}:" | |
w.each_char do |c| | |
@r.zadd key, c.bytes.first, c | |
key += c | |
end | |
@r.zadd key, 0, TERMINAL | |
end | |
def add_words(*words) | |
words.flatten.compact.each {|word| add_word word} | |
end | |
def suggest(text) | |
@r.zrange("#{@prefix}:#{text}", 0, -1).map do |c| | |
(c == TERMINAL) ? text : suggest(text + c) | |
end.flatten | |
end | |
end | |
rt = RedisTrie.new('trie') | |
rt.add_words %w( apple automobile carwash oil-change cranky five ruthie axe auto ) | |
p rt.suggest(ARGV.shift.to_s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment