2012-03-10 21 views
7

我實現了一個函數來組合字母。 簡而言之:紅寶石方式在字符串數組中組合字符集

輸入:[ '汽車', '爲', '土豆', 'RACS', '4', '疤痕', '膏',尖叫']

輸出:[ [「car」,「racs」,「scar」],[「four」],[「for」],[「potatoes」],[「creams」,「scream」]]

我想知道是否有更好的方法來做到這一點。 我真的覺得我用了太多的重複陳述:until,select, delete_if。 有什麼辦法可以結合selectdelete_if陳述嗎?那 的意思是,可以將選中的項目自動刪除?

代碼:

def group_anagrams(words) 
    array = [] 
    until words.empty? 
    word = words.first 
    array.push(words.select { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join) }) 
    words.delete_if { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join) } 
    end 
    array 
end 

由於提前,

+0

[Ruby Anagram Using String#sum]可能的重複(http://stackoverflow.com/questions/9517745/ruby-anagram-using-stringsum) – 2012-03-10 15:59:55

回答

35

就像是:

a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'] 
a.group_by { |element| element.downcase.chars.sort }.values 

輸出是:

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

如果你願意,你可以把這個只有一行到課程的方法。

+6

Ruby編程規則#1:學習Enumerable的方法。規則#2:見規則#1。 :-) – 2012-03-10 15:10:03

+0

奇怪的是,這在我的機器上運行,但不是在heroku!當我在heroku上有這個時,我的網站就停止了... – alexandrecosta 2012-03-16 19:22:33

+0

當我運行這個時,我只得到: – 2014-05-21 17:36:27

0

您可以使用partition功能,而不是選擇在Enumerable實施。它根據決策函數將數組內的條目拆分成兩個數組。

def group_anagrams(words) 
    array = [] 
    until words.empty? 
    word = words.first 
    delta, words = words.partition { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join) }) 
    array += delta 
    end 
    array 
end 

(未經測試)