从Ruby中的列表中获取对的所有组合 [英] Getting all combinations of pairs from a list in Ruby

查看:56
本文介绍了从Ruby中的列表中获取对的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

示例:

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

结果:

l2 #=> [[1,2], [1,3], [1,4], [1,5], [2,3], [2,4], [2,5], [3,4], [3,5], [4,5]]

推荐答案

在Ruby 1.8.6中,您可以使用 Facets :

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

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

In 1.8.7 and later, combination is built-in:

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

这篇关于从Ruby中的列表中获取对的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆