-
-
Save caleywoods/b1fb5aab6893da0ed933 to your computer and use it in GitHub Desktop.
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 combine_anagrams(input) | |
return input.each_with_object(Hash.new []) do |word, hash| | |
hash[word.downcase.sum] += word | |
end.values | |
end | |
# p combine_anagrams %w[cars for potatoes racs four scar creams scream] | |
# => [["cars","racs","scar"], ["for"], ["potatoes"], ["four"], ["creams","scream"]] |
Another alternate solution inspired by the idea of using sum written by Mladen Jablanovic on StackOverflow:
def combine_anagrams(input)
maxlen = input.map(&:length).max
input.group_by {|word|
word.downcase.bytes.map{|b|
maxlen ** (b-'a'.ord)
}.inject(:+)
}.values
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Eloquent solution via @alindeman
Note: rubies prior to 1.9.2 need: