2013-02-17 75 views
0

請看看下面的代碼重構這個代碼,以提高可讀性

def test 
    array = Array.new 
    array2 = Array.new 

    groups = [[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]] 
    type = ["goa", "mumbai"] 
    groups.each_with_index do |item,index| 

     if item.include?(type[0]) == true 
     array << index << array2 
     elsif item.include?(type[1]) == true 
       array2 << index 
     else 
     "nothing ;)" 
     end 

    end 
    print array.each_slice(2).map { |a, b| [a, b.first] } 
end 
combine 

#Output - [[0, 1], [2, 1]] 

見與代碼的問題?那是我使用了一堆if和else語句。如果type數組有多於2個條目會怎麼樣。我不能繼續寫if和elsif語句。那就是我需要你幫忙的地方。什麼是更好的結構代碼?循環?如果是這樣的話。

+0

你究竟想在這裏做什麼?獲取組中的類型索引? – 2013-02-17 12:31:52

+0

是的。所以我正在尋找類型[goa]並在組中鍵入[mumbai]。並將它們導入位置的索引。請注意goa始終處於優先地位。 – psharma 2013-02-17 12:33:43

+0

應該不會輸出[[0,2],[1]]。既然goa在0和2組,而孟買只在1組? – 2013-02-17 12:36:26

回答

2

這是我的代碼。

def combinations(groups, types) 
    array = Array.new(types.size) { Array.new([]) } 
    groups.each_with_index do |item, index| 
    types.each_with_index { |type, i| array[i] << index if item.include? type } 
    end 

    flat = array.inject { |acc, i| acc.product i }.flatten 
    flat.each_slice(types.size).to_a 
end 

樣品測試用例

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "mumbai"]) 

輸出:[[0, 1], [2, 1]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "africa"]) 

輸出:[[0, 2], [2, 2]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"], [123, "india"]], ["goa", "mumbai", "india"]) 

輸出:[[0, 1, 3], [2, 1, 3]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "mumbai", "goa"], [123, "india"]], ["goa", "mumbai", "india", "italy"]) 

輸出:[[0, 1, 3, 0], [0, 2, 3, 0], [2, 1, 3, 0], [2, 2, 3, 0]]

如果我理解正確的話您的問題,那麼這些應該是正確的。雖然我可能誤解了你。請告訴我如果我的問題不對,並且如果你能提供很好的測試用例。

+1

不行我相信你做對了。我只需要稍微調整一下,以適應我更新的情況:)。當然,非常感謝@ahmed – psharma 2013-02-17 13:52:57

+1

。樂於幫助 :) – 2013-02-17 14:28:18