/* In Ruskey's textbook this is Algorithm 4.4: Improved version of Next for combinations in lex order(A(n, k)). The algorithm is NOT memoryless since j is now a global variable. Now we cannot run Next with input that is arbitrary combination and Next will produce the next combination. */ #include #include #define MAX 50 enum BOOLEAN {FALSE, TRUE}; enum BOOLEAN done; int j; void PrintIt(int Array[], int k) { int i; for (i = 0; i < k; i ++) printf(" %d", Array[i]); printf("\n"); } void Next(int Array[], int n, int k) { int i; Array[j] ++; for (i = j+1; i < k; i ++) Array[i] = Array[i-1] + 1; if (j < 0) done = TRUE; if (Array[k-1] < n) j = k-1; else j --; } int main(int argc, char *argv[]) { int n, k, i; int B[MAX+1]; 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 second number must be smaller than the first number."); return 4; } /* Initialize */ for (i = 1; i <= k; i ++) B[i] = i; B[0] = -1; done = FALSE; j = k-1; /* Main loop */ do { PrintIt(B+1, k); Next(B+1, n, k); } while (!done); return 0; }