Note that your iterator is the number of k digits in the base n. In C / C ++, you can represent it as an array of ints size k, where each element is in the range from 0 to n-1 ).
Then, to iterate from one position to another, you only need to increase the number.
This will give you all the permutations. To get combinations, you must impose an additional condition that the numbers must be in ascending order.
For example, with k = 3, n = 3: 000 001 002 011 012 022 111 112 122 222
Implementing this restriction in C is also quite simple in the increment operation used for iteration, instead of setting the rightmost digits to zero, when there is hyphenation, you should set them to the same value as the leftmost digit.
update : some code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXK 100 int main(int argc, char *argv[]) { int digits[MAXK]; int k = atol(argv[1]); int n = atol(argv[2]); int i, left; memset(digits, 0, sizeof(digits)); while(1) { for (i = k; i--; ) { printf("%d", digits[i]); printf((i ? "-" : "\n")); } for (i = k; i--; ) { left = ++digits[i]; if (left < n) { while (++i < k) digits[i] = left; break; } } if (i < 0) break; } }
salva source share