我有一个元素列表(例如数字),我想检索所有可能对的列表。我如何使用 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 :
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
是内置的:
i1 = [1,2,3,4,5]
i2 = i1.combination(2).to_a
关于arrays - 从 Ruby 中的列表中获取对的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573029/