Created
January 8, 2014 15:44
-
-
Save jnd71/8318776 to your computer and use it in GitHub Desktop.
This is a simple ( though not very Ruby idiomatic ) example of how to determine what anagrams exist in a dictionary. The algorithm used is Knuth's anagram algorithm. Idiomatic Ruby has been replaced with an attempt to make the algorithm as readable as possible. Algorithm is O(n), with an additional pass to display / count the number of anagrams.…
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
def load_words | |
formatted_words = [] | |
File.readlines(ARGV[0]).each{|line| formatted_words << line.chomp.downcase} | |
formatted_words | |
end | |
def sort_word_alphabetically(unsorted_word) | |
unsorted_word.chars.sort.join | |
end | |
def sorted_word_hashed?(hash, sorted_word) | |
return false if hash[sorted_word] == nil | |
true | |
end | |
def add_sorted_word_to_hash(word_hash, sorted_word, word) | |
anagram_arr = [] | |
anagram_arr << word | |
word_hash[sorted_word] = anagram_arr | |
end | |
def add_word_to_anagram_arr(word_hash, sorted_word, word) | |
anagram_arr = word_hash[sorted_word] | |
anagram_arr << word | |
word_hash[sorted_word] = anagram_arr | |
end | |
def count_annagrams(word_hash, display_anagrams=false) | |
total = 0 | |
word_hash.each do |key, arr| | |
if arr.length > 1 then | |
total += 1 | |
puts arr.join(" ") if display_anagrams | |
end | |
end | |
total | |
end | |
words = load_words | |
word_hash = Hash.new | |
words.each do |word| | |
sorted_word = sort_word_alphabetically word | |
if sorted_word_hashed?(word_hash, sorted_word) then | |
add_word_to_anagram_arr(word_hash, sorted_word, word) | |
else | |
add_sorted_word_to_hash(word_hash, sorted_word, word) | |
end | |
end | |
puts "Total anagrams ---> #{count_annagrams(word_hash, true)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment