获取k-1长度子集数组的k长度数组[duplicate]

时间:2022-07-02 21:42:44

Possible Duplicate:
ruby array element grouping

可能的重复:ruby数组元素分组

Example. Given array a:

的例子。给数组:

a = [1, 2, 3]

Its length is 3 so I want to print all 2-length arrays. These are:

它的长度是3,所以我想打印所有2长度的数组。这些都是:

[1, 2]
[1, 3]
[2, 3]

I don't know if there is some method in Ruby to get subset arrays. If there is not such a method what is most efficient way to do achieve this.

我不知道Ruby中是否有什么方法可以获得子集数组。如果没有这样的方法,最有效的方法是什么?

1 个解决方案

#1


5  

That's just a simple combination of 2 elements:

这只是两个元素的简单组合:

 >> xs = [1, 2, 3]
 >> xs.combination(xs.size - 1).to_a
 => [[1, 2], [1, 3], [2, 3]]

[EDIT] As @Joshua pointed out in a comment, the docs state that the order is not guaranteed (!). So here is a functional implementation that generates the combinations in the order you asked for. For completeness, I'll make it lazy as the original combination method:

[编辑]正如@Joshua在评论中指出的,文档声明订单没有保证(!)。这是一个功能实现,按你要求的顺序生成组合。为了完整性,我将使它作为原始的组合方法变得懒惰:

require 'enumerable/lazy'

class Array
  def combinations_of(n)
    if n == 0
      [[]].lazy
    else
      0.upto(self.size - 1).lazy.flat_map do |idx|
        self.drop(idx + 1).combinations_of(n - 1).map do |xs| 
          [self[idx]] + xs
        end
      end    
    end
  end
end

#1


5  

That's just a simple combination of 2 elements:

这只是两个元素的简单组合:

 >> xs = [1, 2, 3]
 >> xs.combination(xs.size - 1).to_a
 => [[1, 2], [1, 3], [2, 3]]

[EDIT] As @Joshua pointed out in a comment, the docs state that the order is not guaranteed (!). So here is a functional implementation that generates the combinations in the order you asked for. For completeness, I'll make it lazy as the original combination method:

[编辑]正如@Joshua在评论中指出的,文档声明订单没有保证(!)。这是一个功能实现,按你要求的顺序生成组合。为了完整性,我将使它作为原始的组合方法变得懒惰:

require 'enumerable/lazy'

class Array
  def combinations_of(n)
    if n == 0
      [[]].lazy
    else
      0.upto(self.size - 1).lazy.flat_map do |idx|
        self.drop(idx + 1).combinations_of(n - 1).map do |xs| 
          [self[idx]] + xs
        end
      end    
    end
  end
end