/*---------------------------------------------------------------------------
File name: Perm-noLexic.cpp
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 8/24/2007 01:53:37
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
Here is what I wrote a long long time ago. I used one buffer, but the output
is NOT in lexicographic order.
If you want to the lexicographic order, you can use an extra buffer.
冰的热度's algorithm is one of the best if the numbers are 1..n; if the numbers
are not 1..n, say {1, 3, 4, 6, 9}, you have to modify his algorithm.
C++'s next_permutation() and prev_permutation() work for containers and thus,
in general, you may want to use these two "library" functions instead.
Sample output:
---------------------------------------------------------------------------
1: 1 3
2: 1 4
3: 1 6
4: 1 9
5: 3 4
6: 3 6
7: 3 9
8: 3 1
9: 4 6
10: 4 9
11: 4 1
12: 4 3
13: 6 9
14: 6 1
15: 6 3
16: 6 4
17: 9 1
18: 9 3
19: 9 4
20: 9 6
Press any key to continue . . .
*/
#include <iostream>
using namespace std;
// Permutation of n numbers choose k numbers
// k=1..n.
int a[]={1, 3, 4, 6, 9};
int n=5;
int k=2;
void permute();
void do_permute(int m);
void rotate(int m);
int main()
{
permute();
return 0;
}
void permute()
{
do_permute(n);
}
void do_permute(int m)
{
static int count=0;
if(m==n-k)
{
++count;
cout<<count<<": ";
for(int i=0; i<k; ++i)
cout<<a[i]<<" ";
cout<<endl;
return;
}
for(int i=0; i<m; ++i)
{
do_permute(m-1);
rotate(m);
}
}
void rotate(int m)
{
int t=a[n-m];
for(int i=n-m; i<n; ++i)
a[i]=a[i+1];
a[n-1]=t;
}