我怎样才能简化或清理这个字谜方法? [英] How can I simplify or clean up this anagram method?
本文介绍了我怎样才能简化或清理这个字谜方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里有一个方法,它接受一个字符串数组,并将这些字符串组合在一起,每个组形成一个主 anagram_groups
数组的子数组.
输出很好,但我觉得我的代码可能过于复杂.我的逻辑和/或语法如何简化,而不是将事物重构为更多方法?
def combine_anagrams(words)anagram_groups = []# 对于数组参数中的每个单词word.each 做 |word|# 单词的跟踪变量词添加 = 假anagram_groups.each 做 |group|# 检查单词是否已经存在(防止重复)如果 group.include?单词词添加 = 真# 如果单词是组中第一个字符串的字谜,则将其添加到组中elsif word.downcase.chars.sort == group[0].downcase.chars.sort组<<单词词添加 = 真结尾结尾# 如果单词不是任何字谜,则创建新组(子数组)除非加词anagram_groups <<[单词]词添加 = 真结尾结尾返回 anagram_groups结尾
这是一组用于测试的单词:
test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']
解决方案
test_words.group_by{|w|w.each_char.sort}.values
愿意
<预><代码>[[汽车",赛车",疤痕"],[为了"],[土豆"],[四"],[奶油",尖叫"]]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']
解决方案
test_words.group_by{|w| w.each_char.sort}.values
would give
[
["cars", "racs", "scar"],
["for"],
["potatoes"],
["four"],
["creams", "scream"]
]
这篇关于我怎样才能简化或清理这个字谜方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文