我正在开发类似拼字游戏的应用。在最多15个字母的情况下,它会找到所有可能由该字母组成的有效单词。我决定将字典存储在Trie结构中。我以前的代码是可能的组合,然后查看Trie,如果它们是有效的单词。为了加快速度,我想实施John Pirie的建议posted here。
我正在使用fast_trie gem。附带几个useful methods。
经过几个小时尝试实施John Pirie的解决方案后,我无法回头绕回部分代码。递归算法似乎很少用于ruby - 我很难找到任何帮助。
如何让程序返回上一个节点,检查之前是否存在未采取的路径,搜索并再次返回?
require 'trie'
trie = Trie.read("local_copy_of_my_trie")
input = "helloworld"
rack = input.chars
$words = [] # after recursive search it conains all possible words made from input
start_node = trie.root
def search_from(node, rack)
current_node = node
current_rack = rack
$words.push(node.full_state) if node.terminal?
search_from(choose_next_node(current_node, current_rack), update_rack(current_rack)) # choose next node backtracks if possible
end
def choose_next_node(node, rack)
possible_paths = []
rack.each { |l| possible_paths.push(l) if $trie.has_children?(node.full_state+l) }
# must backtrack if there are no possibilities
# how to mark path as already taken?
# can i return both node and rack to search_from ?
end
def update_rack(rack)
# how to update rack not knowing the result of choose_next_node here?
end
search_from(start_node, rack)