问题
I have a method here that takes an array of strings and groups the ones that are anagrams of each other together, with each group forming a sub-array of the main anagram_groups
array.
The output is fine but I feel like my code is probably overly-complicated. How could my logic and/or syntax be simplified, short of refactoring things into more methods?
def combine_anagrams(words)
anagram_groups = []
# For each word in array argument
words.each do |word|
# Tracking variable for the word
word_added = false
anagram_groups.each do |group|
# Check if word already exists (prevents duplicates)
if group.include? word
word_added = true
# Add word to group if it is an anagram of the first string in the group
elsif word.downcase.chars.sort == group[0].downcase.chars.sort
group << word
word_added = true
end
end
# If word was not an anagram of anything, create new group (subarray)
unless word_added
anagram_groups << [word]
word_added = true
end
end
return anagram_groups
end
This is an array of words for testing:
test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']
回答1:
test_words.group_by{|w| w.each_char.sort}.values
would give
[
["cars", "racs", "scar"],
["for"],
["potatoes"],
["four"],
["creams", "scream"]
]
回答2:
I modified sawa's answer slightly in order to ignore case and make sure there's no duplicate values:
test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!}
I realize this will still give duplicates in the output if the words have characters with different cases, but that's fine for my purposes. Now I'm all sorted, thanks!
来源:https://stackoverflow.com/questions/16631961/how-can-i-simplify-or-clean-up-this-anagram-method