/* Algorithm 4.5 in Ruskey's textbook: Recursive procedure for generating B(n, k) in lex order. */ #include #include #define MAX 50 int n, k; void PrintIt(int Array[]) { int i; for (i = 0; i < n; i ++) printf(" %d", Array[i]); printf("\n"); } void Combs(int Array[], int j, int m) { /* Array[j] is the cell we are about to fill in. */ /* m is the number of 1's placed so far in Array. */ int i; /* It is j-1 >= n-1, actually :) */ if (j >= n) PrintIt(Array); else { /* k-m is the number of 1's we have yet to place in Array. */ /* n-j is the number of cells from Array[j+1] to Array[n-1], incl. */ if (k-m < n-j) { /* Array[j+1, ..., n-1] has enough room for k-m 1's. */ Array[j] = 0; Combs(Array, j+1, m); } if (k-m > 0) { /* We have to place more 1's into Array. */ Array[j] = 1; Combs(Array, j+1, m+1); } } } int main(int argc, char *argv[]) { int i; int B[MAX]; if (argc != 3) { printf("\n Two arguments expected.\n"); return 1; } k = atoi(argv[1]); n = atoi(argv[2]); if (n < 0 || k < 0) { printf("\n Positive numbers expected.\n"); return 2; } if (n > MAX || k > MAX) { printf("\n Numbers not greater than %d expected.\n", MAX); return 3; } if (k > n) { printf("\n The first number must not be greater than the second number.\n"); return 4; } Combs(B, 0, 0); return 0; }