Ruby 我如何简化或清理这个字谜法?
我这里有一个方法,它获取一个字符串数组,并将互为字谜的字符串分组在一起,每组组成主Ruby 我如何简化或清理这个字谜法?,ruby,anagram,Ruby,Anagram,我这里有一个方法,它获取一个字符串数组,并将互为字谜的字符串分组在一起,每组组成主字谜组数组的子数组 输出很好,但我觉得我的代码可能过于复杂了。我的逻辑和/或语法如何简化,而不是重构成更多的方法 def combine_anagrams(words) anagram_groups = [] # For each word in array argument words.each do |word| # Tracking variable for the word w
字谜组数组的子数组
输出很好,但我觉得我的代码可能过于复杂了。我的逻辑和/或语法如何简化,而不是重构成更多的方法
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
会给
[
["cars", "racs", "scar"],
["for"],
["potatoes"],
["four"],
["creams", "scream"]
]
会给
[
["cars", "racs", "scar"],
["for"],
["potatoes"],
["four"],
["creams", "scream"]
]
我稍微修改了sawa的答案,以忽略大小写,并确保没有重复值:
test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!}
我意识到如果单词有不同大小写的字符,输出中仍然会有重复的字符,但这对我来说没关系。现在我都整理好了,谢谢 为了忽略大小写并确保没有重复值,我稍微修改了sawa的答案:
test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!}
我意识到如果单词有不同大小写的字符,输出中仍然会有重复的字符,但这对我来说没关系。现在我都整理好了,谢谢 哇,这要简洁得多,看起来分组法做了很多艰苦的工作。如果你不介意我问的话,它是从哪里来的?我在阵列文档中看不到任何提及。哦,对了,谢谢。让我们看看我是否做对了:在数组上使用可枚举方法group_by生成数组的排序散列(取决于块中的内容),然后values方法从散列中获取值(即子数组)并将其粘贴到新数组中?哇,这更简洁了,看起来“方法小组”做了很多艰苦的工作。如果你不介意我问的话,它是从哪里来的?我在阵列文档中看不到任何提及。哦,对了,谢谢。让我们看看我是否做对了:在数组上使用可枚举方法group_by生成数组的排序哈希(取决于块中的内容),然后values方法从该哈希中获取值(即子数组),并将它们粘贴到新数组中?