用全排列的方式生成一个数列的随机排列(C++实现)

Question: 

 

input :     n

 

output:    A random permutation of [0 ..  n-1]

 

ie:  

input: 5

output: 0 3 2 4 1 

 

// Type your C++ code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).

#include <iostream>
using namespace std;

typedef vector<int> List;

// print series
void printList(List arr) {
    List::iterator it = arr.begin();
    while(it != arr.end()) {
        cout<<*it<<" ";
        it ++;
    }
    cout<<endl;
}

int ck = 0;

// base iteration function
void iterPermutation(List &list, int l, int h, List &ret, int &k) {    
    if(l > h) {
        k--;
        if(k == 0) ret = list;
        return;
    }
    for(int i = l; i <= h; i++) {
        swap(list[i], list[l]);
        iterPermutation(list, l+1, h, ret, k);
        swap(list[i], list[l]);
    }
}

// factorial of n
int factorial(int n) {
    if(n == 0) return 1;
    return n * factorial(n-1);
}

// generate a random permutation of [1 .. n-1]
List randomSeries(int n) {
    List vec;
    for(int i = 0; i < n; i++) vec.push_back(i);
    
    List ret;
    int r = rand() % factorial(n);
    iterPermutation(vec, 0, n-1, ret, r);
    
    return ret;
}

int main() {
    int n = 5;
    cout<<"n = "<<factorial(n)<<endl;
    printList(randomSeries(n));
    
    return 0;
}

 

 欢迎关注微信公众号——计算机视觉 

 

你可能感兴趣的:(C++)