在保留序列的同时获取数组项的所有组合 - Ruby

时间:2010-08-11 10:25:59

标签: ruby arrays sequence combinations

给定一个字符串数组

["the" "cat" "sat" "on" "the" "mat"]

我希望从任何起始位置依次获得所有项目组合,例如

["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]

不允许使用原始序列或缺少元素的组合,例如

["sat" "mat"] # missing "on"
["the" "on"]  # reverse order

我还想知道这个操作是否有一个特定的名称,或者是否有一种更简洁的方式来描述它。

感谢。

3 个答案:

答案 0 :(得分:6)

如果你是单行,你可以尝试

(0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}

BTW,我认为这些被称为数组的“所有子序列”。

答案 1 :(得分:4)

在每个可能的结束位置上迭代每个起始位置和每个起始位置:

arr = ["the", "cat", "sat", "on", "the", "mat"]
(0 ... arr.length).map do |i|
  (i ... arr.length).map do |j|
    arr[i..j]
  end
end.flatten(1)
#=> [["the"], ["the", "cat"], ["the", "cat", "sat"], ["the", "cat", "sat", "on"], ["the", "cat", "sat", "on", "the"], ["the", "cat", "sat", "on", "the", "mat"], ["cat"], ["cat", "sat"], ["cat", "sat", "on"], ["cat", "sat", "on", "the"], ["cat", "sat", "on", "the", "mat"], ["sat"], ["sat", "on"], ["sat", "on", "the"], ["sat", "on", "the", "mat"], ["on"], ["on", "the"], ["on", "the", "mat"], ["the"], ["the", "mat"], ["mat"]]

flatten(1)需要ruby 1.8.7+(或backports)。

答案 2 :(得分:0)

在这里你可以得到所有的组合

(1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)
相关问题