Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- void perm_show(int *p, int n) {
- for (int i = 0; i < n; i++) {
- printf("%d", p[i]);
- if (i < n - 1) printf(" ");
- }
- puts("");
- }
- void perm_put(int *p, bool *ok, int n, int pos, int k) {
- p[pos] = k;
- if (pos == n - 1) perm_show(p, n);
- else {
- ok[k] = false;
- for (int i = 1; i <= n; i++) {
- if (ok[i]) perm_put(p, ok, n, pos + 1, i);
- }
- ok[k] = true;
- }
- }
- void generate_permutation(void) {
- const int n = 4;
- int p[n];
- bool ok[n + 1];
- for (int i = 1; i <= n; i++) ok[i] = true;
- for (int i = 1; i <= n; i++) perm_put(p, ok, n, 0, i);
- return;
- }
- unsigned int first(unsigned int n) {
- return (unsigned int)((1U << n) - 1U);
- }
- unsigned int next_comb(unsigned int x) {
- unsigned int smallest = x & -x;
- unsigned int ripple = x + smallest;
- unsigned int new_smallest = ripple & -ripple;
- unsigned int ones = ((new_smallest / smallest) >> 1U) - 1U;
- return ripple | ones;
- }
- void print_comb(unsigned int c, int n) {
- for (int i = 0; i < n; i++) {
- if (c & 1U) {
- printf("%d", i + 1U);
- if (i < n - 1) printf(" ");
- }
- c >>= 1U;
- }
- puts("");
- }
- void generate_combination(void) {
- const unsigned int n = 8;
- const unsigned int k = 4;
- unsigned int x = first(k);
- for (int i = 1; !(x & ~first(n)); i++, x = next_comb(x)) print_comb(x, n);
- return;
- }
- int main(void) {
- puts("Permutation");
- generate_permutation();
- puts("");
- puts("Combination");
- generate_combination();
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement