Last active
September 9, 2018 19:43
-
-
Save AlexAvlonitis/df971e994ef9bfa91842cd917c8f10ff to your computer and use it in GitHub Desktop.
Anagram Kata Ruby - http://codekata.com/kata/kata06-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
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