Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all combinations of pairs from a list in Ruby

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]]
like image 539
Christian Stade-Schuldt Avatar asked Oct 15 '09 15:10

Christian Stade-Schuldt


People also ask

How do you get all possible array combinations in Ruby?

Ruby | Array combination() operation Array#combination() : combination() is an Array class method which invokes with a block yielding all combinations of length 'n' of elements of the array. Syntax: Array.

What is .first in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.

How do I find an element in an array in Ruby?

The find method locates and returns the first element in the array that matches a condition you specify. find executes the block you provide for each element in the array. If the last expression in the block evaluates to true , the find method returns the value and stops iterating.

What is the opposite of include in Ruby?

exclude? is defined as ! include?, meaning it is the exact opposite of include? . See the source. This means that it works for Arrays and Hashes too, as well as for Strings.


2 Answers

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
like image 183
Pesto Avatar answered Nov 04 '22 01:11

Pesto


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]]}}
like image 34
glenn mcdonald Avatar answered Nov 04 '22 01:11

glenn mcdonald