2012-01-14 115 views
11

的順序亞羣說給出一個列表的列表

{"a", "b", "c", "d"} 

有沒有產生這樣的順序子集的列表更簡單的方法(結果的順序並不重要)

{ 
{"a"}, 
{"a b"}, 
{"a b c"}, 
{"a b c d"}, 
{"b"}, 
{"b c"}, 
{"b c d"}, 
{"c"}, 
{"c d"}, 
{"d"} 
} 

回答

19

我想我喜歡這個最重要的是:

set = {"a", "b", "c", "d"}; 

ReplaceList[set, {___, x__, ___} :> {x}] 

隨着字符串加入:

ReplaceList[set, {___, x__, ___} :> "" <> Riffle[{x}, " "]] 

與此類似,具體爲字符串:

StringCases["abcd", __, Overlaps -> All] 

由於納賽爾說我作弊,這裏是一個更手動的辦法,也有大型成套更高的效率:

ClearAll[f, f2] 
f[i_][x_] := NestList[i, x, [email protected] - 1] 
f2[set_] := Join @@ (f[Most] /@ f[Rest][set]) 

f2[{"a", "b", "c", "d"}] 
+0

+1,這是不公正的先生,你讓Mathematica用這種方法做所有的辛苦工作。你應該做點什麼! – Nasser 2012-01-14 13:31:13

+0

這是神奇的,不是編程! – acl 2012-01-14 13:36:54

+3

這太棒了!我認爲這與Mathematica的核心概念非常吻合,而不是作弊:) – Silvia 2012-01-14 15:32:42

1

你可以像這樣做:

a = {"a", "b", "c", "d"}; 
b = List[StringJoin[Riffle[#, " "]]] & /@ 
    Flatten[Table[c = Drop[a, n]; 
    Table[Take[c, i], {i, Length[c]}], 
    {n, 0, Length[a]}], 1] 

輸出將是這樣的:

{{"a"}, {"a b"}, {"a b c"}, {"a b c d"}, {"b"}, {"b c"}, {"b c d"}, {"c"}, {"c d"}, {"d"}} 
1

這裏是一個可能的解決方案

a={"a","b","c","d"}; 
[email protected][#, " "] & /@ 
    DeleteDuplicates[ 
    LongestCommonSubsequence[a, #] & /@ 
    DeleteCases[[email protected], {}]] // Column 

結果

a 
b 
c 
d 
a b 
b c 
c d 
a b c 
b c d 
a b c d 
7

如何:

origset = {"a", "b", "c", "d"}; 

bdidxset = Subsets[Range[4], {1, 2}] 

origset[[#[[1]] ;; #[[-1]]]] & /@ bdidxset 

這給

{{"a"}, {"b"}, {"c"}, {"d"}, {"a", "b"}, {"a", "b", "c"}, {"a", "b", 
    "c", "d"}, {"b", "c"}, {"b", "c", "d"}, {"c", "d"}} 
1

單程:

makeList[lst_] := Map[ Union[lst[[1 ;; #]]] &, [email protected][lst]] 
r = Map[makeList[lst[[# ;; -1]]] &, [email protected][lst]]; 
Flatten[r, 1] 

給出

{{"a"}, 
{"a", "b"}, 
{"a", "b", "c"}, 
{"a", "b", "c", "d"}, 
{"b"}, 
{"b", "c"}, 
{"b", "c", "d"}, 
{"c"}, 
{"c", "d"}, 
{"d"}} 
14
Flatten[Partition[{a, b, c, d}, #, 1] & /@ {1, 2, 3, 4}, 1] 

給出

{{A},{B},{C},{d},{一,b},{b,c},{c,d},{a,b,c},{b,c,d},{a, b,c,d}}

+0

+1 ,比巫師先生複雜得多,但還是不錯的。 – rcollyer 2012-01-16 02:50:13

5

我喜歡TomD的方法更好,但這是來到我的腦海裏,SANS字符串處理:

set = {"a", "b", "c", "d"}; 

n = [email protected]; 

Join @@ Table[set~Take~{s, f}, {s, n}, {f, s, n}] // Column 

Mathematica graphics

+1

爲什麼兩個答案? – abcd 2012-01-14 15:36:49

+1

@yoda更多代表,當然 – 2012-01-14 17:45:27

+3

@yoda我認爲答案是充分不同的性格。我看到一個綜合性答案的問題:不清楚人們投票選擇哪種方法,貶低投票的目的,選民可能會覺得如果他們想要投票,他們必須爲不喜歡的方法投票(或徹底失敗)爲他們所做的一票投票。與彼得的斷言相反,我不是在玩遊戲票。 – 2012-01-15 00:02:30

相關問題