Advertisement
gsimon75

permutation.cc

Feb 25th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. // Index <-> Permutation
  2.  
  3. // Compile: g++ -Wall -o p permutation.cc
  4.  
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <stdint.h>
  8.  
  9. #define N       5
  10. #define NFACT   120
  11.  
  12. void
  13. index_to_permutation(uint32_t n, int permutation[N]) {
  14.     uint32_t nf = NFACT;
  15.     for (int i = 0; i < N; ++i) {
  16.         nf /= N - i;
  17.         permutation[i] = n / nf;
  18.         n %= nf;
  19.     }
  20.  
  21.     // convert from index-in-remainining-items to permutation
  22.     for (int i = 0; i < N - 1; ++i) {
  23.         for (int j = i + 1; j < N; ++j) {
  24.             if (permutation[j] >= permutation[i])
  25.                 permutation[j] += 1;
  26.         }
  27.     }
  28. }
  29.  
  30. uint32_t
  31. permutation_to_index(const int orig_permutation[N]) {
  32.     uint32_t permutation[N];
  33.     memcpy(permutation, orig_permutation, N * sizeof(permutation[0]));
  34.  
  35.     // convert from permutation to index-in-remainining-items
  36.     for (int i = 0; i < N - 1; ++i) {
  37.         for (int j = i + 1; j < N; ++j) {
  38.             if (permutation[j] > permutation[i])
  39.                 permutation[j] -= 1;
  40.         }
  41.     }
  42.  
  43.     uint32_t index = 0;
  44.     uint32_t nf = 1;
  45.     for (int i = 1; i < N; ++i) {
  46.         index += nf * permutation[N - i];
  47.         nf *= i;
  48.     }
  49.    
  50.     return index;
  51. }
  52.  
  53. int
  54. main(void) {
  55.     int p[N];
  56.     for (int i = 0; i < 10; ++i) {
  57.         // convert from index i to permutation p
  58.         index_to_permutation(i, p);
  59.         // convert permutation p back to index j -> check if i == j
  60.         uint32_t j = permutation_to_index(p);
  61.  
  62.         // dump i, p, j
  63.         printf("p(%d) = ", i);
  64.         for (int k = 0; k < N; ++k)
  65.             printf("%c%d", (k == 0) ? '[': ',', p[k]);
  66.         printf("] = p(%d)\n", j);
  67.     }
  68.     return 0;
  69. }
  70.  
  71. // vim: set sw=4 ts=4 et:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement