Skip to content

Instantly share code, notes, and snippets.

@ewoodh2o
Created March 5, 2012 18:54
Show Gist options
  • Save ewoodh2o/1980340 to your computer and use it in GitHub Desktop.
Save ewoodh2o/1980340 to your computer and use it in GitHub Desktop.
# Solves Stanford's SAAS anagram question
# http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf
# Question 3
def combine_anagrams(words)
# Set up a hash to hold the groups:
# Keys will be the sorted anagram string
# Values will be the array of anagrams for that string
# Hash works well here because it's a fast lookup on
# the key, even when the words array gets really long.
groups = {}
# Iterate over the words list
words.each do |word|
# Find the anagram key, which is the sorted lowercase letters
# "ElliottWood" becomes "deillooottw"
chars = word.downcase.chars.sort.join
# Key into the groups hash for that anagram key
# Set it to an empty array if it doesn't exist,
# then append the current word to that array.
groups[chars] ||= []
groups[chars] << word
end
# The Hash#values fetches the arrays without
# the keys, which is the desired return format.
groups.values
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment