【问题标题】:How can I simplify or clean up this anagram method?我怎样才能简化或清理这个字谜方法?
【发布时间】:2013-05-13 23:23:29
【问题描述】:

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

【问题讨论】:

    标签: ruby anagram


    【解决方案1】:
    test_words.group_by{|w| w.each_char.sort}.values
    

    会给

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

    【讨论】:

    • 哇,这更简洁了,看起来 group_by 方法做了很多艰苦的工作。如果你不介意我问,它来自哪里?我在数组的文档中看不到任何提及它。
    • 哦,好的,谢谢。所以让我们看看我是否做对了:在数组上使用可枚举方法 group_by 来生成数组的排序散列(取决于块中的内容),然后 values 方法获取值(即子数组)从该哈希中提取并将它们粘贴到一个新数组中?
    【解决方案2】:

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

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

    我意识到如果单词的字符大小写不同,这仍然会在输出中出现重复,但这对我的目的来说很好。现在我都整理好了,谢谢!

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多