Skip to content

Instantly share code, notes, and snippets.

@AlexAvlonitis
Last active September 9, 2018 19:43
Show Gist options
  • Save AlexAvlonitis/df971e994ef9bfa91842cd917c8f10ff to your computer and use it in GitHub Desktop.
Save AlexAvlonitis/df971e994ef9bfa91842cd917c8f10ff to your computer and use it in GitHub Desktop.
class Anagram
attr_reader :results
def initialize(word_list)
file = File.open(word_list).read
@words_hash_map = {}
@words_array = []
@results = {}
puts "Loading file..."
file.each_line do |line|
chomped_line = line.chomp
sorted = sorted_word(chomped_line)
if @words_hash_map[sorted].is_a? Array
@words_hash_map[sorted] << chomped_line
else
@words_hash_map[sorted] = [chomped_line]
end
@words_array << chomped_line
end
end
def anagrams
start_time = Time.now
puts "Calculating..."
@words_array.each do |word|
sorted = sorted_word(word)
@results[sorted] = @words_hash_map[sorted]
end
@results.reject! { |key, value| value.count == 1 }
"Took: #{Time.now - start_time} seconds"
end
private
def sorted_word(word)
word.split('').sort.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment