hash - Tweaking a T9 Trie in Ruby to append new words -
this implementation of t9 trie generator has major flaw. it's overwriting previous words added tree rather appending them. i'm not surprised @ it, stumped...
class trie def initialize @root = hash.new end # loop here def build(word) node = @root t9num = word.tr('a-z', '22233344455566677778889999') t9num.each_char |ch| node[ch] ||= hash.new node = node[ch] end node[:end] = "#{word}" end def find(str) node = @root str.each_char |ch| return nil unless node = node[ch] end node[:end] && true end end these commands:
t = trie.new t.build('buy') t.build('build') t.build('builder') t.build('act') t.build('acu') puts t.inspect output this:
#<trie:0x0000010103ea60 @root={"2"=>{"8"=>{"9"=>{:end=>"buy"}, "4"=>{"5"=>{"3"=>{:end=>"build", "3"=>{"7"=>{:end=>"builder"}}}}}}, "2"=>{"8"=>{:end=>"acu"}}}}>
it seems me problem in line:
node[:end] = "#{word}" here node[:end] can 1 word, , overwritten if 2 words have same sequence of t9 keys. try instead:
(node[:end] ||= []) << word this way have array of words @ end of branch. don't forget check if word in trie.
Comments
Post a Comment