由网友(酒言欢)分享简介:我有哈希的哈希值。这个散列有一本字典。我需要找到它具有同根的所有比赛。例如,我有:#<特里:0x00000001bf9a40 @根= {米=> {一个=> {×=> {:年底=>如此,我=> {M=> {:年底=>如此,我=> {M=> {L=> {I=...
我有哈希的哈希值。这个散列有一本字典。我需要找到它具有同根的所有比赛。例如,我有:
#<特里:0x00000001bf9a40 @根= {
米=> {一个=> {×=> {
:年底=>如此,
我=> {M=> {
:年底=>如此,
我=> {M=> {L=> {I=> {A=> {N=> {:年底=>真}} }}}}
}},
在w=> {的e=> {升=> {升=> {:端=>真}}}}
}}}
}>
和字最大
,格言
,马克西米利安
,麦克斯韦
。我如何获得所有单词本哈希的根源在哪里?例如
T = Trie.new
t.add(.....#现在我们添加的单词
t.find(最大)
#result它开始从最大的所有单词
t.find('格言')
#result它开始从'格言'=&GT的一切话,格言,马克西米利安
解决方案
它看起来像我的查找
方法是非常相似的@萨瓦的。 (我相信@sawa是谁第一个教我用注
与&放人;:[]
的情况下,这像这样的,所以这是件)。
由于:
班特里
高清初始化(根)
@root =根#只是一个快捷方式,使用您的数据,并专注于您的问题
结束
#通过哈希递归`h`找到所有单词开头的`s`
高清字(H,S,A = [])
h.each做| K,V |
如果k ==:结束
A<<小号
其他
字(V,S + K,A)
结束
结束
一个
结束
私募:字
DEF找到(开始)
字(start.chars.inject(@root,和放大器;:[]),开始)救援[]
结束
结束
T = Trie.new({M=> {A=> {X=> {:年底=>如此,
我=> {M=> {:年底=>如此,
我=> {M=> {L=> {I=> {A=> {N=> {:年底=>真}} }}}}}},
在w=> {的e=> {升=> {升=> {:端=>真}}}}}}}})
您可以做的:
t.find(最大)
#=> [最大,格言,maximimlian,麦斯威尔]
t.find('马克西')
#=> [格言,maximimlian]
t.find('maximi)
#=> [maximimlian]
t.find('maxw)
#=> [麦克斯韦]
t.find('×')
#=> []
I have a hash of hashes. This hash has a dictionary. I need to find all matches in it which have the same root. For example, I have:
#<Trie:0x00000001bf9a40 @root={
"m"=>{"a"=>{"x"=>{
:end=>true,
"i"=>{"m"=>{
:end=>true,
"i"=>{"m"=>{"l"=>{"i"=>{"a"=>{"n"=>{:end=>true}}}}}}
}},
"w"=>{"e"=>{"l"=>{"l"=>{:end=>true}}}}
}}}
}>
and words "max"
, "maxim"
, "maximilian"
, "maxwell"
. How do I get all words in this hash by the root? For example
t = Trie.new
t.add( .....# now we added words
t.find('max')
#result all words which begins from 'max'
t.find('maxim')
#result all words which begins from 'maxim' => maxim, maximilian
解决方案
It looks like my find
method is very similar to @sawa's. (I believe @sawa is the person who first taught me to use inject
with &:[]
in cases this like this, so that's fitting.)
Given:
class Trie
def initialize(root)
@root = root # Just a shortcut to use your data and focus on your question
end
# Recurses through Hash `h` to find all words starting with `s`
def words(h, s, a=[])
h.each do |k, v|
if k == :end
a << s
else
words(v, s+k, a)
end
end
a
end
private :words
def find(start)
words(start.chars.inject(@root, &:[]), start) rescue []
end
end
t = Trie.new({"m"=>{"a"=>{"x"=>{:end=>true,
"i"=>{"m"=>{:end=>true,
"i"=>{"m"=>{"l"=>{"i"=>{"a"=>{"n"=>{:end=>true}}}}}}}},
"w"=>{"e"=>{"l"=>{"l"=>{:end=>true}}}}}}}})
You can do:
t.find('max')
# => ["max", "maxim", "maximimlian", "maxwell"]
t.find('maxi')
# => ["maxim", "maximimlian"]
t.find('maximi')
# => ["maximimlian"]
t.find('maxw')
# => ["maxwell"]
t.find('x')
# => []
相关推荐
最新文章