从Ruby中的列表中获取对的所有组合

时间:2020-12-28 19:26:36

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?

我有一个元素列表(例如数字),我想检索所有可能的对的列表。我怎么能用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]]

2 个解决方案

#1


26  

In Ruby 1.8.6, you can use Facets:

在Ruby 1.8.6中,您可以使用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:

在1.8.7及更高版本中,组合是内置的:

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

#2


8  

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]]}}

#1


26  

In Ruby 1.8.6, you can use Facets:

在Ruby 1.8.6中,您可以使用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:

在1.8.7及更高版本中,组合是内置的:

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

#2


8  

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]]}}