Question

I have a list of elements (e.g. numbers) and I want to retrieve a list of all possible pairs. How can I do that using Ruby?

Example:

l1 = [1, 2, 3, 4, 5]

Result:

l2 #=> [[1,2], [1,3], [1,4], [1,5], [2,3], [2,4], [2,5], [3,4], [3,5], [4,5]]
Was it helpful?

Solution

In Ruby 1.8.6, you can use Facets:

require 'facets/array/combination'
i1 = [1,2,3,4,5]
i2 = []
i1.combination(2).to_a # => [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

In 1.8.7 and later, combination is built-in:

i1 = [1,2,3,4,5]
i2 = i1.combination(2).to_a

OTHER TIPS

Or, if you really want a non-library answer:

i1 = [1,2,3,4,5]
i2 = (0...(i1.size-1)).inject([]) {|pairs,x| pairs += ((x+1)...i1.size).map {|y| [i1[x],i1[y]]}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top