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.
谢谢。
3 个解决方案
#1
4
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)
.
flatten(1)需要ruby 1.8.7+(或后台端口)。
#2
6
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
0
here you can get all the combinations
这里你可以得到所有的组合
(1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)
#1
4
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)
.
flatten(1)需要ruby 1.8.7+(或后台端口)。
#2
6
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
0
here you can get all the combinations
这里你可以得到所有的组合
(1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)