#include <stdio.h>
#include <vector>
#include <random>
#include <chrono>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
/*
Author:Marco
Date:2018/4/21
Aim:序列随机化的常用两种算法
*/
/*
1.什么是随机化的序列
---得到该序列的概率是1/n!(错误的理解是该序列每个元素出现的概率是1/n)
*/
void print_vector(const vector<int>& vec) {
for (auto& v : vec) {
cout << v << ends;
}
cout << endl;
}
int partition(const int& lo, const int& hi, vector<int>& vec, vector<int>& key) {
int i = lo;
int j = hi + 1;
while (true) {
while (key[lo] > key[++i]) if (i == hi) break;
while (key[lo] < key[--j]) if (j == lo) break;
if (i >= j) break;
int temp = key[j];
key[j] = key[i];
key[i] = temp;
temp = vec[i];
vec[i] = vec[j];
vec[j] = temp;
}
int temp = key[j];
key[j] = key[lo];
key[lo] = temp;
temp = vec[j];
vec[j] = vec[lo];
vec[lo] = temp;
return j;
}
void quick_sort(const int& lo, const int& hi, vector<int>& vec, vector<int>& key) {
if (lo >= hi) {
return;
}
int j = partition(lo, hi, vec, key);
quick_sort(lo,j - 1, vec, key);
quick_sort(j + 1, hi, vec, key);
}
void quick_sort(vector<int>& vec, vector<int> key) {
quick_sort(0, vec.size() - 1, vec, key);
print_vector(key);
}
//main 1
/*
因为priority序列是均匀分布的,即vec的第一个元素优先级最小的概率是1/n(n为序列大小)
以此类推可得获得vec序列的情况为1/n * 1/(n-1)....=1/n!满足随机序列情况
*/
void shuffle_vector1(vector<int>& vec) {
vector<int>::size_type size = vec.size();
vector<int> priority;
auto t = chrono::system_clock::now().time_since_epoch().count();
static default_random_engine e(t);
static uniform_int_distribution<int> u(1, static_cast<int>(pow(size, 3)));
for (int i = 0; i < size; ++i) {
priority.push_back(u(e));
}
quick_sort(vec, priority);
}
//main 2
/*
我们知道对于一个n个元素的序列的k排列(k<=n)有n!/(n - k)!种
第二种算法每次迭代前vec包含这个i - 1排列的概率是 (n - i + 1)! / n!(序列首元素假定从1开始)
迭代到序列末可得到包含n排列的概率是1/n!
*/
void shuffle_vector2(vector<int>& vec) {
auto t = chrono::system_clock::now().time_since_epoch().count();
default_random_engine e(t);
for (int i = 0; i < vec.size(); ++i) {
uniform_int_distribution<int> u(i, vec.size() - 1);
std::swap(vec[i], vec[u(e)]);
}
}
int main() {
vector<int> vec{ 0,1,2,3,4,5,6,7,8,9 };
print_vector(vec);
shuffle_vector1(vec);
print_vector(vec);
shuffle_vector2(vec);
print_vector(vec);
system("pause");
return 0;
}
随机序列常用算法
最新推荐文章于 2021-05-24 09:28:23 发布