Last active
December 1, 2016 01:08
-
-
Save tdlm/751915592fb32f039d7dd49032e9dc14 to your computer and use it in GitHub Desktop.
Trie w/ Ruby
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
#!/bin/ruby | |
class Trie | |
@@root | |
def initialize | |
@@root = TrieNode.new | |
end | |
def add_word(word) | |
current = @@root | |
word.split('').each do |chr| | |
node = current.get_node(chr) | |
if !node.is_a?(TrieNode) | |
node = TrieNode.new | |
current.add_node(chr, node) | |
end | |
current = node | |
end | |
current.set_end_of_word | |
end | |
def count_prefix_words(prefix) | |
current = @@root | |
prefix.split('').each do |chr| | |
node = current.get_node(chr) | |
return 0 if !node.is_a?(TrieNode) | |
current = node | |
end | |
children = current.get_children | |
return walk_and_count_word_ends(children) | |
end | |
def walk_and_count_word_ends(array) | |
count = 0 | |
class Trie | |
@@root | |
def initialize | |
@@root = TrieNode.new | |
end | |
def add_word(word) | |
current = @@root | |
word.split('').each do |chr| | |
node = current.get_node(chr) | |
if !node.is_a?(TrieNode) | |
node = TrieNode.new | |
current.add_node(chr, node) | |
end | |
current = node | |
end | |
current.set_end_of_word | |
end | |
def count_prefix_words(prefix) | |
current = @@root | |
prefix.split('').each do |chr| | |
node = current.get_node(chr) | |
return 0 if !node.is_a?(TrieNode) | |
current = node | |
end | |
children = current.get_children | |
return walk_and_count_word_ends(children) | |
end | |
def walk_and_count_word_ends(array) | |
count = 0 | |
array.each do |key, item| | |
if item.is_end_of_word | |
count += 1 | |
end | |
count += walk_and_count_word_ends(item.get_children) | |
end | |
return count | |
end | |
def output | |
puts @@root.get_children | |
end | |
end | |
class TrieNode | |
def initialize | |
@children = Hash.new | |
@end_of_word = false | |
end | |
def get_node(chr) | |
return @children[chr] if @children.key?(chr) | |
end | |
def add_node(chr, node) | |
@children[chr] = node | |
end | |
def is_end_of_word | |
@end_of_word | |
end | |
def set_end_of_word | |
@end_of_word = true | |
end | |
def get_children | |
@children | |
end | |
def has_children | |
@children.length > 0 | |
end | |
attr_accessor :children | |
attr_accessor :end_of_word | |
end | |
trie = Trie.new() | |
trie.add_word("happy") | |
trie.add_word("ham") | |
trie.add_word("hart") | |
puts trie.count_prefix_words("h") # 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment