Last active
July 29, 2017 18:25
-
-
Save maxjacobson/20537debf7d9d14685d3a8211f8df0ac to your computer and use it in GitHub Desktop.
This file contains 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
# usage: | |
# ruby trie.rb chatter | |
word = ARGV.first || ["chatter", "helio", "wonder", "gosli"].sample | |
class Node | |
def add(chars) | |
return if chars.empty? | |
char = chars.shift | |
children[char] ||= Node.new | |
children[char].add(chars) | |
end | |
def autocomplete(start) | |
start. | |
chars. | |
inject(self) { |node, char| node[char] }. | |
flatten. | |
map { |finish| start + finish } | |
end | |
protected | |
def [](k) | |
@children[k] or raise "doesn't seem to be a word :/" | |
end | |
def flatten | |
children.flat_map do |char, child_node| | |
fafa = child_node.flatten.map { |thingy| char + thingy } | |
if fafa.any? | |
fafa | |
else | |
[char] | |
end | |
end | |
end | |
private | |
def children | |
@children ||= {} | |
end | |
end | |
require "benchmark" | |
root = nil | |
bm1 = | |
Benchmark.realtime do | |
words = File.read("/usr/share/dict/words").lines | |
root = Node.new | |
words.each do |word| | |
root.add(word.chomp.split("")) | |
end | |
end | |
bm2 = Benchmark.realtime { puts root.autocomplete(word) } | |
puts "Building trie: #{bm1}s" | |
puts "Autocomplete: #{bm2}s" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment