2010-08-11 22 views
2

考慮到字符串數組獲得的數組項的所有組合,同時保留序列 - 紅寶石

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

我也想知道這個操作是否有一個特定的名字,或者如果有一個更好的方式來描述它。

謝謝。

回答

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

需要Ruby 1.8.7+(或反向移植),用於flatten(1)

+0

我把編輯範圍的自由使用'的...''而不是-1'。另請注意,Ruby 1.9.2引入了'flat_map',它基本上等價於map {}。flatten(1)'。也可用'backports' :-) – 2010-08-11 14:30:36

6

如果你到一個俏皮話,你可以嘗試

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

順便說一句,我認爲那些被稱爲數組的「所有子序列」。

+0

他問的是子串,而不是子串。每個子字符串也是一個子序列,但並不是所有的子序列都是子字符串。例如,'235'是'123456'的子序列,但不是子字符串。 – 2010-08-11 15:35:34

+0

謝謝,我不知道差異。因此,子串必須是原始數組中的連續元素,而子串則不需要。 – 2010-08-11 16:12:30

+0

在任何情況下,上述是找到子字符串,而不是子序列,所以,只是語義...優雅的解決方案:) – butterywombat 2014-10-22 10:35:41

0

在這裏你可以得到所有的組合

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