Created
June 12, 2024 16:50
-
-
Save roa-sh/8dfea3efab56b105965656dc6c11d91d to your computer and use it in GitHub Desktop.
Anagrams Ruby Exercise
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
#* Write a Ruby method group_anagrams that takes an array of strings as input | |
#* and groups the anagrams together. | |
#* Anagrams are words or phrases formed by rearranging the letters of another. | |
def group_anagrams(words) | |
groups = {} | |
words.each_with_index do |word, index| | |
sorted_word = word.chars.sort.join | |
if groups[sorted_word].nil? | |
groups[sorted_word] = [word] | |
else | |
groups[sorted_word] << word | |
end | |
end | |
groups | |
end | |
words = ['cat', 'tea', 'eat', 'ate', 'bat', 'eattt', 'tac', 'cct'] | |
puts group_anagrams(words) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment