如何在Ruby中将单词数组排序为字谜数组?

时间:2013-04-06 20:08:12

标签: ruby arrays string hash anagram

http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf

尝试参与此作业的第3部分。以下代码似乎不起作用,即对于参数['HeLLo', 'hello'],返回[["hello"], ["HeLLo"]]而不是[["HeLLo", "hello"]]

def combine_anagrams(words)
    #iterate through words, make hashmap with the sorted version
    hash = {}
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] = []
    end

    #iterate through words, access hashmap and append curr to array
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] << x
    end

    hash.values #return array of values
end

任何帮助将不胜感激。 (我是Ruby新手)

1 个答案:

答案 0 :(得分:1)

您可以轻松地这样做:

def combine_anagrams(words)
  anagrams={}
      words.each do |word|
        anagrams[word.downcase.split('').sort.join] ||=[]
        anagrams[word.downcase.split('').sort.join] << word 
      end
      anagrams.values
end