Main Page | Class Hierarchy | Class List | File List | Class Members | File Members

mdp_permutations.h

Go to the documentation of this file.
00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 // this is my favourite piece of code...
00014 
00015 
00016 // this is just n!
00017 long mdp_permutations(int n) {
00018   long a=1;
00019   for(;n;n--) a*=n;
00020   return a;
00021 }
00022 
00023 // this sorts the first k elements of map[] assuming 
00024 // the fisrt k-1 are already sorted
00025 void mdp_permutation_sort(int map[], int k) {
00026   int i, tmp;
00027   for(i=k-1; i>=0; i--)
00028     if(map[i]>map[i+1]) {
00029       tmp=map[i];
00030       map[i]=map[i+1];
00031       map[i+1]=tmp;
00032     }
00033 }
00034 
00042 int mdp_permutation(int n, int k, int i) {
00043   int* map=new int[i+1];
00044   int j,l,m;
00045 
00046   if(i>n || k>mdp_permutations(n)) return -1;
00047 
00048   for(j=0; j<=i; j++) {
00049     map[j] = (k % mdp_permutations(n-j)) / mdp_permutations(n-1-j);
00050     mdp_permutation_sort(map, j-1);
00051     for(l=0; l<j; l++)
00052       if(map[l]<=map[j]) map[j]++;    
00053     if(i==j) {
00054       m=map[j];
00055       delete[] map;
00056       return m; 
00057     }
00058   }
00059   delete[] map;
00060   return -1;
00061 }

Generated on Sun Feb 27 15:12:21 2005 by  doxygen 1.4.1