我在这里有一个方法,它采用一个字符串数组并将彼此的字谜组合在一起,每个组形成主数组的子anagram_groups
数组。
输出很好,但我觉得我的代码可能过于复杂。如果不将事物重构为更多方法,我的逻辑和/或语法怎么能被简化?
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
这是一组用于测试的单词:
test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']