2012-06-07 21 views
2

如何在不包括[object i, object j][object j, object i]的情況下自己完成陣列的笛卡爾積?陣列本身的笛卡爾積沒有紅寶石中的副本

目前,我有

array = %w{a b c} 
unique_combinations = array.each_with_index.to_a.product(array.each_with_index.to_a). 
    find_all{|(first_object, i), (second_object, j)| i < j}. 
    map{|(first_object, i), (second_object, j)| [first_object, second_object]} 
unique_combinations # => [["a", "b"], ["a", "c"], ["b", "c"]] 

其作品,但感覺有點冗長。

我能做

array = %w{a b c} 
combinations = array.product(array) 
unique_combinations = combinations.find_all{|first_item, second_item| array.index(first_item) < array.index(second_item)} 

但感覺就像我扔的信息了,並且只會如果數組只有在它獨特的項目工作。

另一種方法是

unique_combinations = [] 
array.each_with_index do |first_item, i| 
    array.each_with_index do |second_item, j| 
    next unless i < j 
    unique_combinations << [first_item, second_item] 
    end 
end 

但感覺太迫切,而不是功能。

回答

6

它被稱爲combination

a = %w{a b c} 

a.combination(2).to_a 
=> [["a", "b"], ["a", "c"], ["b", "c"]]