2

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.

1 Answer 1

6

It's called a combination?

a = %w{a b c}

a.combination(2).to_a
=> [["a", "b"], ["a", "c"], ["b", "c"]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.