2013-04-06 27 views
2

http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf如何将单词数组排序为Ruby中的字符串数组?

试图参与本作业的第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)

+0

给我们输入的字符串,并预期输出。 – 2013-04-06 20:18:03

+1

这个问题就在前些日子,搜索了一下。另外,如果你想分组,也许'group_by'方法是你应该看的。 – tokland 2013-04-06 20:18:28

+0

试试这个'hash.values.flatten(1).reverse.each_cons(2){| x | p [x]} – 2013-04-06 20:25:00

回答

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 
+1

检查重复的问题,看看更好的方法:http://stackoverflow.com/questions/9646995/ruby​​-way-to-do-this – tokland 2013-04-06 20:55:31

+0

+1,正在寻找group_by选项来纠正我自己:) 我要离开这里,我不想复制其他人的代码,虽然我确实想要用'group_by'做点什么。每个人都在寻找更好的选项来检查@toklands链接。 thnx @tokland – Zippie 2013-04-06 20:57:07

相关问题