So if
list={1,2,3}
then output should be
{{},{1},{2},{3},{1,2},{2,3},{1,2,3}}
or in different order.
So if
list={1,2,3}
then output should be
{{},{1},{2},{3},{1,2},{2,3},{1,2,3}}
or in different order.
In version 10.4 you can use
Subsequences[{1, 2, 3}]
(* {{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}} *)
One way is this:
Catenate@Table[
Take[list, {i, j}],
{i, Length[list]}, {j, i, Length[list]}
]
Catenate@ instead of Join@@, because the latter is a bit slower).
– Martin Ender
Apr 03 '16 at 18:51
One can use SequenceCases starting from version 10.1:
Union@SequenceCases[{1, 2, 3}, {___}, Overlaps -> All]
{{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}}
Or, if you don't want the empty list:
SequenceCases[{1, 2, 3}, {__}, Overlaps -> All]
{{1, 2, 3}, {1, 2}, {1}, {2, 3}, {2}, {3}}
Sort[Join[{{}}, ReplaceList[list, {___, x__, ___} :> {x}]]]
{{}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}}
Also:
ClearAll[f]
f[lst_] := With[{indices = List /@ Join @@ (Partition[Range[Length@lst], #, 1] & /@
Range[Length@lst])}, Extract[lst, indices]]
f[{a, b, c, d}]
{{a}, {b}, {c}, {d}, {a, b}, {b, c}, {c, d}, {a, b, c}, {b, c, d}, {a, b, c, d}}
If you need to include {}:
Prepend[f[{a, b, c, d}], {}]
{}, notice that the OP added that to the question only after he posted his own answer with Subsets ... which doesn't return what he asked for even after this update to the question.
– Szabolcs
Apr 03 '16 at 08:46
in:= Subsets[list]
out:= {{},{1},{2},{3},{1,2},{2,3},{1,2,3}}
{1,3} or do you want all sublists of contiguous elements as your example suggests?
– Szabolcs
Apr 03 '16 at 08:35
Unionbit. – Simon Woods Apr 03 '16 at 19:44Catenate @instead ofJoin @@and new timings. – Martin Ender Apr 03 '16 at 20:49