C++編寫生成不反復的隨機數代碼。本站提示廣大學習愛好者:(C++編寫生成不反復的隨機數代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是C++編寫生成不反復的隨機數代碼正文
C++編寫生成不反復的隨機數代碼
vector<int> getRandom(int total)
{
srand((int)time(NULL));
std::vector<int> input = *new std::vector<int>();
for (int i = 0; i < total; i++) {
input.push_back(i);
}
vector<int> output = *new vector<int>();
int end = total;
for (int i = 0; i < total; i++) {
vector<int>::iterator iter = input.begin();
int num = random()%end;
iter = iter+num;
output.push_back(*iter);
input.erase(iter);
end--;
}
return output;
}
再來一例:
void permutation(int n, int *z_array)
{
int i, j, k, z;
int buffer[N];
/* 初始化數組 */
for (i=0; i<n; i++)
buffer[i]=0;
/* 預備生成隨機數,以以後時光為種子 */
srand((unsigned)time((long *)0));
/* 取得不反復的隨機數據 */
for (i=0; i<n; i++) {
/* 取得0~(n-i)的隨機數據 */
z = rand()%(n-i);
j=0; k=0;
while (j<=z) {
if (buffer[j+k]==0) j++;
else k++;
}
buffer[j+k-1]=1;
z_array[i]=j+k-1;
}
return;
}
辦法三:來個龐雜點的
#include<stdio.h>
#include <time.h>
#include "iostream"
#include <math.h>
#define N 53
using namespace std;
//print array
void display(int *a)
{
for (int i =0;i<N;i++)
{
cout<<" "<<a[i]<<" ";
}
}
int main(void)
{
int b[N],a[N];
for (int i =0;i<N;i++)
{
b[i] = i+1;
}
// random(a);
srand((unsigned)time(NULL));
int MaxIndex = N;
for ( i= 0;i<N;i++)
{
//
int index = (int)rand()%MaxIndex;//隨機一個 0 - 52的index
a[i] = b[index]; //隨機到的數字給a[i],i from 0 to N-1
b[index] = b[MaxIndex-1];
MaxIndex--;
}
display(a);
return 0;
}
以上3種辦法都可完成生成不反復的隨機數,詳細的效力若何,小同伴們本身測試下吧。