Last active
January 7, 2017 17:39
-
-
Save gonzedge/ca899231dbdc2765b0e66f824dc0fdc3 to your computer and use it in GitHub Desktop.
Find all substrings that are words with a(n uncompressed) trie
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
#!/usr/bin/env bash | |
chmod +x ./substrings.rb | |
# with the words with friends dictionary found in | |
# https://github.com/gonzedge/rambling-trie/blob/master/assets/dictionaries/words_with_friends.txt | |
./substrings.rb 'ifdxawesome45someword3' # => | |
# aw | |
# awe | |
# awes | |
# awesome | |
# es | |
# if | |
# me | |
# mew | |
# om | |
# or | |
# so | |
# some | |
# we | |
# wo | |
# word |
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
#!/usr/bin/env ruby | |
require 'set' | |
require 'rambling-trie' | |
trie = Rambling::Trie.create '/the/path/to/your/favorite/dictionary' | |
def substrings trie, letters | |
# Use set to avoid repeated words | |
results = Set.new | |
chars = letters.chars | |
# Have to use send because #root is private :( | |
root = trie.send(:root) | |
(0..(chars.length - 1)).each do |starting_index| | |
get_substrings root, chars.slice(starting_index..(chars.length - 1)), results | |
end | |
# Sort results in alphabetical order | |
results.to_a.sort | |
end | |
def get_substrings node, chars, results | |
results << node.to_s if node.terminal? | |
unless chars.empty? | |
key = chars.slice!(0).to_sym | |
if node[key] | |
get_substrings node[key], chars, results | |
end | |
end | |
end | |
puts substrings(trie, ARGV.first) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment