Ollie Glass
Ollie Glass

Reputation: 19993

Getting all combinations of array items while preserving sequence - Ruby

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.

Upvotes: 2

Views: 2731

Answers (3)

rajagopal
rajagopal

Reputation: 49

here you can get all the combinations

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

Upvotes: 0

sepp2k
sepp2k

Reputation: 370102

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).

Upvotes: 4

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

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.

Upvotes: 6

Related Questions