7
$\begingroup$

Need some help listing all sub-sequences of a number:

X=219

The output should be:

{2,21,219,1,19,9}

Order does not matter for this problem.

Any help is appreciated.

$\endgroup$
0

6 Answers 6

7
$\begingroup$

You can use a combination of IntegerDigits + Subsequences + FromDigits:

FromDigits /@ Rest @ Subsequences[IntegerDigits @ #] & @ 219
{2, 1, 9, 21, 19, 219}
$\endgroup$
4
$\begingroup$
X = 219;

FromDigits /@ ReplaceList[IntegerDigits[X], {___, x__, ___} -> {x}]

{2, 21, 219, 1, 19, 9}

$\endgroup$
3
$\begingroup$
X = 219; 
Y = IntegerDigits[X]; 
FromDigits /@(Y[[#[[1]] ;; #[[2]]]] & /@
Flatten[Table[{i, j}, {i, 1, Length[Y]}, {j, i, Length[Y]}], 1])

gives

{2, 21, 219, 1, 19, 9}

Note that

Flatten[Table[{i, j}, {i, 1, Length[Y]}, {j, i, Length[Y]}], 1]

is

{{1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 3}}

the set of pairs of starting position and ending position.

$\endgroup$
3
$\begingroup$
Subsets[IntegerDigits@219, {1, 3}]

gives

{{2}, {1}, {9}, {2, 1}, {2, 9}, {1, 9}, {2, 1, 9}}

If you do not want the three-length set, then use

Subsets[IntegerDigits@219, {1, 2}]
$\endgroup$
3
$\begingroup$

Using SequenceCases with its All- option

SequenceCases[IntegerDigits[219], x : {__} :> FromDigits[x], Overlaps -> All]

{219, 21, 2, 19, 1, 9}

$\endgroup$
3
$\begingroup$

Using Sequences:

ToExpression["" <> ## & @@@ Subsequences[Characters@ToString@219, {1, 3}]]

(*{2, 1, 9, 21, 19, 219}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.