Skip to content

Instantly share code, notes, and snippets.

@roa-sh
Created June 12, 2024 16:50
Show Gist options
  • Save roa-sh/8dfea3efab56b105965656dc6c11d91d to your computer and use it in GitHub Desktop.
Save roa-sh/8dfea3efab56b105965656dc6c11d91d to your computer and use it in GitHub Desktop.
Anagrams Ruby Exercise
#* 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