I've looked around online for an non-recursive k-combinations algorithm, but have had trouble understanding all of the reindexing involved; The code I've found online is not commented well, or crashes.
For example, if I have the collection, {'a', 'b', 'c', 'd', 'e'} and I want to find a 3 combinations; ie,
abc abd abe acd ace ade bcd bce bde cde How can I implement an algorithm to do this? When I write down the general procedure, this it is clear. That is; I increment the last element in a pointer until it points to 'e', increment the second to last element and set the last element to the second to last element + 1, then increment the last element again until it reaches 'e' again, and so on and so forth, as illustrated by how I printed the combinations. I looked at Algorithm to return all combinations of k elements from n for inspiration, but my code only prints 'abc'. Here is a copy of it:
#include <stdio.h> #include <stdlib.h> static void comb(char *buf, int n, int m) { // Initialize a pointer representing the combinations char *ptr = malloc(sizeof(char) * m); int i, j, k; for (i = 0; i < m; i++) ptr[i] = buf[i]; while (1) { printf("%s\n", ptr); j = m - 1; i = 1; // flag used to denote that the end substring is at it's max and // the j-th indice must be incremented and all indices above it must // be reset. int iter_down = 0; while((j >= 0) && !iter_down) { // if (ptr[j] < (n - i) ) { iter_down = 1; ptr[j]++; for (k = j + 1; k < m; k++) { ptr[k] = ptr[j] + (k - j); } } else { j--; i++; } } if (!iter_down) break; } } int main(void) { char *buf = "abcde"; comb(buf, 5, 3); return 1; }
char *ptr = malloc(sizeof(char) * m);-->char *ptr = malloc(sizeof(char) * (m+1));if (ptr[j] < (n - i) ) {: It has compared the letters and numbers. It is always false case of this sample code.(j--... only once "abc")