如何简化或清理这个anagram方法?

时间:2013-05-19 06:14:28

标签: ruby anagram

我这里有一个方法,它接受一个字符串数组,并将彼此的字符串组合在一起,每个组形成一个主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']

2 个答案:

答案 0 :(得分:3)

test_words.group_by{|w| w.each_char.sort}.values

会给出

[
  ["cars", "racs", "scar"],
  ["for"],
  ["potatoes"],
  ["four"],
  ["creams", "scream"]
]

答案 1 :(得分:0)

我稍微修改了sawa的答案,以便忽略大小写并确保没有重复的值:

test_words.group_by{|w| w.downcase.each_char.sort}.values.each{|v| v.uniq!}

我意识到如果单词具有不同情况的字符,这仍然会在输出中给出重复项,但这对我的目的来说很好。现在我整理好了,谢谢!