I need to generate all integers such that they start with 1, have exactly k distinct digits, and every next digit is at most by 1 larger than the maximum of the preceding ones (10 is replaced with 0). At the moment I am using the following recursive function:
TotalDigits=10;
DistinctDigits=4;
b[n_, m_] :=
b[n, m] =
If[n == 1, {{1}},
Table[Append[#, Mod[i, 10]], {i, 1, Min[Max[#] + 1, m]}] & /@
b[n - 1, m] // Flatten[#, 1] &];
FromDigits /@
Select[b[TotalDigits, DistinctDigits],
CountDistinct[#] == DistinctDigits &]
This works when the number of distinct digits is small but becomes very ineffective when it gets larger, as too many unnecessary elements are generated that are later filtered out by the Select
function. Can anyone suggest how to optimize this so that I do not need to generate too many elements at the intermediate step? In particular, b[10,10] should return only one element, {1,2,3,4,5,6,7,8,9,0}
, but my current code runs out of memory before it can calculate this.
I saw a somewhat related question here: Generating Tuples with restrictions
However, I doubt that the solution proposed there, which uses IntegerPartitions
, is of any use in my case, because the sum is not constrained.