The problem is actually similar to counting in base sizeof (set) by length k (assuming the set has a maximum of 10 elements).
For example, when typing { 0, 1, 2 }
along a length of 2, you count from 00
to 22
, base 3 ..
In order to solve the βonly unambiguous changeβ restriction, instead of counting it more and more often, do this only until the next change of 10 th . Then decrease the score, then again more often, etc.
For example, in the example above
00 -> 02 then increase the next tenth (12), then count downward 12 -> 10 then again +10 to get 20, then go up again 20 -> 22
At length 3, keep the same reasoning, change the next 10 th then go up or down depending on the initial value of the current digit
000 -> 002, 012 -> 010, 020 -> 022 122 -> 120, 110 -> 112, 102 -> 100 200 -> 202, 212 -> 210, 220 -> 222
A recursive algorithm is one approach. Function depth 0 processes the first (left) digit, i.e. The highest is 10 th and counts up or down depending on the current state of the digit. If 0
, count otherwise. For each state, before the increment, the function calls itself recursively with the next (right) digital status (which is either 0
or the last element in the set). Maximum depth is length k.
Save the status of digits in an array of length k. The array is initialized to {0 ... 0}
. Give the function the index in the array (starting at 0). For each iteration, if we are at maximum depth (i.e. i == k-1
), print an array; otherwise call the recursive function with i+1
.
Pseudo code
k length of number (number of digits) N size of set (1 .. 10), values from 0 to N-1 A array of size k A[0 .. k-1] = 0 function f ( i ) begin inc = -1 if (A[i] > 0), 1 otherwise
This is what you should get for N = 3, and k = 4
0000 0001 0002 0012 0011 0010 0020 0021 0022 0122 0121 0120 0110 0111 0112 0102 0101 0100 0200 0201 0202 0212 0211 0210 0220 0221 0222 1222 1221 1220 1210 1211 1212 1202 1201 1200 1100 1101 1102 1112 1111 1110 1120 1121 1122 1022 1021 1020 1010 1011 1012 1002 1001 1000 2000 2001 2002 2012 2011 2010 2020 2021 2022 2122 2121 2120 2110 2111 2112 2102 2101 2100 2200 2201 2202 2212 2211 2210 2220 2221 2222
Please note that you should always get N k ...
This is the C code that generated above:
int a[20] = {0}; // Put here the right size instead of 20, or use
in main()
initialize N
and k
and call
f(0);
Iterative version that does basically the same thing
void fi() { int z,i,inc[k]; for(i=0 ; i<k ; i++) { a[i] = 0; // initialize our array if needed inc[i] = 1; // all digits are in +1 mode } int p = k-1; // p, position: start from last digit (right) while(p >= 0) { if (p == k-1) { for(z=0 ; z<k ; z++) printf("%d", a[z]); printf("\n"); } if (inc[p]<0 && a[p]>0 || inc[p]>0 && a[p]<N-1) { a[p] += inc[p]; p = k-1; } else { inc[p] = -inc[p]; p--; } } }