Getting all combinations of array items while pres

2019-07-16 09:35发布

问题:

Given an array of strings

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

I'm looking to get all combinations of items in sequence, from any starting position, e.g.

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

Combinations out of the original sequence or with missing elements are disallowed, e.g.

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

I'd also like to know if this operation has a particular name or if there's a neater way of describing it.

Thanks.

回答1:

Just iterate over each starting position and for each starting position over each possible end position:

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

Requires ruby 1.8.7+ (or backports) for flatten(1).



回答2:

If you're into one-liners, you might try

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

BTW, I think those are called "all subsequences" of an array.



回答3:

here you can get all the combinations

(1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)