Advertisement
cd62131

Permutations and Combinations

Jan 29th, 2014
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. void perm_show(int *p, int n) {
  5.   for (int i = 0; i < n; i++) {
  6.     printf("%d", p[i]);
  7.     if (i < n - 1) printf(" ");
  8.   }
  9.   puts("");
  10. }
  11. void perm_put(int *p, bool *ok, int n, int pos, int k) {
  12.   p[pos] = k;
  13.   if (pos == n - 1) perm_show(p, n);
  14.   else {
  15.     ok[k] = false;
  16.     for (int i = 1; i <= n; i++) {
  17.       if (ok[i]) perm_put(p, ok, n, pos + 1, i);
  18.     }
  19.     ok[k] = true;
  20.   }
  21. }
  22. void generate_permutation(void) {
  23.   const int n = 4;
  24.   int p[n];
  25.   bool ok[n + 1];
  26.   for (int i = 1; i <= n; i++) ok[i] = true;
  27.   for (int i = 1; i <= n; i++) perm_put(p, ok, n, 0, i);
  28.   return;
  29. }
  30. unsigned int first(unsigned int n) {
  31.   return (unsigned int)((1U << n) - 1U);
  32. }
  33. unsigned int next_comb(unsigned int x) {
  34.   unsigned int smallest = x & -x;
  35.   unsigned int ripple = x + smallest;
  36.   unsigned int new_smallest = ripple & -ripple;
  37.   unsigned int ones = ((new_smallest / smallest) >> 1U) - 1U;
  38.   return ripple | ones;
  39. }
  40. void print_comb(unsigned int c, int n) {
  41.   for (int i = 0; i < n; i++) {
  42.     if (c & 1U) {
  43.       printf("%d", i + 1U);
  44.       if (i < n - 1) printf(" ");
  45.     }
  46.     c >>= 1U;
  47.   }
  48.   puts("");
  49. }
  50. void generate_combination(void) {
  51.   const unsigned int n = 8;
  52.   const unsigned int k = 4;
  53.   unsigned int x = first(k);
  54.   for (int i = 1; !(x & ~first(n)); i++, x = next_comb(x)) print_comb(x, n);
  55.   return;
  56. }
  57. int main(void) {
  58.   puts("Permutation");
  59.   generate_permutation();
  60.   puts("");
  61.   puts("Combination");
  62.   generate_combination();
  63.   return EXIT_SUCCESS;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement