The function next
updates the array a
to the next number, returning the value of the bottom digit. The main
function iterates through the sequence, stopping once the top digit is 10 (since once the array has been used up, next
just keeps incrementing the most significant digit).
The algorithm, in words and ignoring bounds checking, could be described as "to find the next number, add one to the bottom digit, and if it overflows find the next number ignoring the bottom digit, and then duplicate the new bottom digit."
#include <stdio.h>
int next(int *a, size_t len) {
if (*a == 9 && len > 1) {
*a = next(a-1, len-1);
} else {
*a += 1;
}
return *a;
}
#define N 6
int main(int argc, char *argv[]) {
int a[N] = {0};
while (next(a+N-1, N) != 10) {
for (int i = 0; i < N; i++) {
if (a[i] != 0) printf("%d", a[i]);
}
printf("\n");
}
return 0;
}
You can count the solutions in O(N) time (where N is the number of digits). If K(n, d) is the number of solutions with exactly n digits, and whose top digit is 9-d, then K(0, d) = 1, and K(n+1, d) = K(n, 0) + K(n, 1) + ... + K(n, d). The number of solutions with n or fewer digits is then K(1, 8) + K(2, 8) + ... + K(n, 8). These observations yield this dynamic programming solution:
int count(int n) {
int r[9] = {1};
int t = 0;
for (int i = 0; i < n+1; i++) {
for (int j = 1; j < 9; j++) {
r[j] += r[j-1];
}
t += r[8];
}
return t - 1;
}
int main(int argc, char* argv[]) {
printf("there are %d numbers.\n", count(6));
return 0;
}
Gives:
there are 5004 numbers.