1
$\begingroup$

Update

A very crude attemp

myfun[n_] := Block[{PlaceValue},
    PlaceValue = IntegerDigits@n;

    If[
        FreeQ[PlaceValue, 9],
        PlaceValue[[-1]] = PlaceValue[[-1]] + 1,
        If[
            AllTrue[PlaceValue, # == 9 &],
            PlaceValue = Table[2, Length@PlaceValue + 1],
            PlaceValue[[First@FirstPosition[PlaceValue, 9] - 1 ;;]] = PlaceValue[[First@FirstPosition[PlaceValue, 9] - 1]] + 1
        ]
    ];
    FromDigits@PlaceValue
];
myfun[999]
myfun[299999]
myfun[22258]
myfun[2249]
myfun[2489]

as a function.

OP

I want to write a code that is able to iteratively create a list that looks like this:

l2 = Table[FromDigits@{i, j}, {i, 2, 9}, {j, i, 9}] // Flatten;
l3 = Table[FromDigits@{i, j, k}, {i, 2, 9}, {j, i, 9}, {k, j, 9}] // Flatten;
l4 = Table[FromDigits@{i, j, k, l}, {i, 2, 9}, {j, i, 9}, {k, j, 9}, {l, k, 9}] // Flatten;
desiredList = Flatten[{l2, l3, l4}]

That is, the next number is the smallest(first) number that all the digits are in non-decreasing order. I can manully do this for numbers up to 26 digits until I ran out of letters to use and then move on to use double letter for the iterators, but I am wondering if there is a better way to creat it? I want to use it for large number that has 60/70 digits and maybe even larger.

It can be a function that takes a number for example,

 f[344] = 345
 f[348] = 349
 f[349] = 355
 f[399] = 444

and

f[9999] = 22222

ect.

Or some kind of iterative formula that I can use in a While or Fold loop?

Thanks.

$\endgroup$
3
$\begingroup$
f = x \[Function] 10 x + Range[Mod[x, 10], 9];
F = X \[Function] Join @@ f[X];
result = Join @@ Rest@NestList[F, Range[2, 9], 3];
result == desiredList

True

$\endgroup$
2
$\begingroup$

An alternate approach is to define the function

f[n_] := Module[{c, d=IntegerDigits[n], e=IntegerDigits[n + 1]},             
    c=Count[d, 9]; FromDigits @ If[c==Length[d],
    ConstantArray[1, c + 1], e/.{0 -> e[[-Count[d - e, 9] - 1]]}]];

and then create the lists with code such as

ln[n_] := NestWhileList[f, 2 (10^(n+1) - 1)/9, # < 10^(n+1) - 1&];

For example:

ln[2]
(* 22, 23, 24, 25, 26, 27, 28, 29, 33, 34, 35, 36, 37, 38, 39, 44, 45, 46, 47, 48, 49, 55, 56, 57, 58, 59, 66, 67, 68, 69, 77, 78, 79, 88, 89, 99} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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