Created
December 27, 2021 19:12
-
-
Save matu3ba/cc622062c493c0737cc19b016aac0733 to your computer and use it in GitHub Desktop.
combinations with repitition iterative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
const char *donuts[] = {"iced", "jam", "plain", | |
"something completely different"}; | |
int pos[] = {0, 0, 0, 0}; | |
void printDonuts(int k) { | |
for (size_t i = 1; i < k + 1; i += 1) // offset: i:1..N, N=k+1 | |
printf("%s\t", donuts[pos[i]]); // str:0..N-1 | |
printf("\n"); | |
} | |
// idea: custom number system with 2s complement like 0b10...0==MIN stop case | |
int step_comb_with_rep(int n, int k) { | |
pos[k] += 1; // xxxxN -> xxxxN+1 | |
for (int i = k; i > 0; i -= 1) { | |
if (pos[i] > n - 1) // if number spilled over: xx0(n-1)xx | |
{ | |
pos[i - 1] += 1; // set xx1(n-1)xx | |
for (int j = i; j <= k; j += 1) | |
pos[j] = pos[j - 1]; // set xx11..1 | |
} | |
} | |
if (pos[0] > 0) // stop condition: 1xxxx | |
return 1; // true | |
return 0; // false | |
} | |
int main() { | |
int n = 3; | |
int k = 2; | |
printDonuts(k); | |
while(step_comb_with_rep(n, k) == 0) | |
printDonuts(k); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment