Created
July 29, 2013 21:18
-
-
Save vjdhama/6107943 to your computer and use it in GitHub Desktop.
Edx 169.1x Hw 1-3
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
#!/usr/bin/env ruby | |
class String | |
def sort_by_char | |
self.downcase.split(//).sort.join # Handle all test cases | |
end | |
end | |
def combine_anagrams(words) | |
sorted_arr = [] | |
words.each do |word| | |
sorted_arr << word.sort_by_char | |
end | |
sorted_arr.uniq! | |
result = [] | |
sorted_arr.each do |word| | |
result << words.select { |w| w.sort_by_char == word } | |
end | |
result | |
end | |
#Alternative One Liner | |
#def combine_anagrams(words) | |
# words.group_by {|i| i.downcase.chars.sort.join}.values | |
#end | |
puts combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
anagrams cool man, let my internship finish i'll catch up with you..:)