How can I do a cartesian product of an array with itself, without including both [object i, object j] and [object j, object i]?
Currently, I've got
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"]]
which works, but feels a little verbose.
I could do
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)}
but that feels like I'm throwing information away, and would only work if the array only had unique items in it.
Another approach is
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
but that feels too imperative rather than functional.