Skip to content

Instantly share code, notes, and snippets.

@chewbranca
Created November 16, 2010 21:28
Show Gist options
  • Save chewbranca/702546 to your computer and use it in GitHub Desktop.
Save chewbranca/702546 to your computer and use it in GitHub Desktop.
Find string permutations using a Trie
class Trie
attr_accessor :value, :children
def initialize value = ''
@value = value
@children = {}
end
def [] val
@children[val]
end
def []= val, trie
@children[val] = trie
end
def next_val char
self.value + char
end
def to_s
puts @value unless @value.empty?
@children.each {|c| c.to_s }
nil
end
def self.build_trie str, root = nil
root ||= Trie.new
str.each_char do |char|
# To allow duplicates switch these lines
rest = str.delete char
#rest = str.sub char, ''
root[char] ||= Trie.build_trie(rest, Trie.new(root.next_val(char)))
end
root
end
end
Trie.build_trie('aac').to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment