2013-03-31 54 views
1

我是一個新手,我不知道從哪裏去。輸入是單詞陣列 - 輸出應該是對陣列進行分組的數組陣列。

def combine_anagrams(words) 
    a1 = [] 
    words.sort do |x, y| 
     a = x.downcase.chars.sort.join 
     b = y.downcase.chars.sort.join 
     if a == b 
      a1.push(x,y) 
     end 
    end 
end 

x = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'] 
combine_anagrams(x) 

我使用的排序方法數組中,因爲它是我發現它可以讓我通過它的陣列來比較兩個元素的唯一方法。任何和所有的幫助,非常感謝!

回答

2
x.group_by{|s| s.downcase.chars.sort}.values 
# => [["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]] 
+1

非常好!我認爲他們都是成對的,並且錯過了他們會有三倍或單打的可能性。 –

+0

這就是這樣。我只提出一個變量的重命名:'x' - >'words','s' - >'word'。 – tokland

+0

這是偉大的sawa謝謝你!你能否詳細說明在我的代碼中替換的內容以及它的放置位置。我不斷收到未定義的方法錯誤。 – ltrainpr

0

查閱關於combination的文檔。 http://www.ruby-doc.org/core-2.0/Array.html#method-i-combination

嘗試這樣的事情(未經測試

def combine_anagrams(words) 
    a1 = [] 
    words.combination(2).each do |x, y| 
     a = x.downcase.chars.sort.join 
     b = y.downcase.chars.sort.join 
     if a == b 
      a1.push(x,y) 
     end 
    end 
end 

x = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'] 
combine_anagrams(x) 
0

如果你正在尋找所有可能字謎,你可能不希望只比較兩個元素一次。你是否打算忽略只包含單個項目的字謎(例如,在你的例子中爲'for')?因此,你可能應該使用一次迭代每個元素的不同函數。

後 - 事實上

@sawa看法是正確的,我想。它結合了你想要實現的正確性和Ruby的簡潔性。