Skip to content

Instantly share code, notes, and snippets.

@caleywoods
Created March 1, 2012 14:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caleywoods/b1fb5aab6893da0ed933 to your computer and use it in GitHub Desktop.
Save caleywoods/b1fb5aab6893da0ed933 to your computer and use it in GitHub Desktop.
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"]]
@caleywoods
Copy link
Author

def combine_anagrams(input)
  input.group_by { |word| word.downcase.chars.sort }.values
end

Eloquent solution via @alindeman

Note: rubies prior to 1.9.2 need:

def combine_anagrams(input)
  input.group_by { |word| word.downcase.split("").sort }.values
end

@caleywoods
Copy link
Author

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