Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential Subsets of a list

Given a list say

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

Is there any easier way to generate list of sequential subsets like this (order of the result is not important)

{
 {"a"},
 {"a b"},
 {"a b c"},
 {"a b c d"},
 {"b"},
 {"b c"},
 {"b c d"},
 {"c"},
 {"c d"},
 {"d"}
}
like image 815
Prashant Bhate Avatar asked Jan 14 '12 10:01

Prashant Bhate


2 Answers

I think I like this best of all:

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

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

With the string joining:

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

In a similar vein, specific to strings:

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

Since Nasser says I am cheating, here is a more manual approach that also has greater efficiency on large sets:

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

f2[{"a", "b", "c", "d"}]
like image 89
Mr.Wizard Avatar answered Sep 18 '22 19:09

Mr.Wizard


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

gives

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

like image 43
681234 Avatar answered Sep 20 '22 19:09

681234