2013-04-06 49 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

相關問題