2

如何在不同时包含[object i, object j]and的情况下对数组进行笛卡尔积[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

但这感觉太迫切而不是实用。

4

1 回答 1

6

这叫组合

a = %w{a b c}

a.combination(2).to_a
=> [["a", "b"], ["a", "c"], ["b", "c"]]
于 2012-06-07T01:44:52.740 回答