Created
March 5, 2012 18:54
-
-
Save ewoodh2o/1980340 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
# 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