C++編寫生成不重復的隨機數代碼
更新時間:2015年05月19日 15:43:49 投稿:hebedich
本文給大家匯總介紹了3種c++實現(xiàn)生成不重復的隨機數的函數,十分的簡單實用,有需要的小伙伴可以參考下。
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種方法均可實現(xiàn)生成不重復的隨機數,具體的效率如何,小伙伴們自己測試下吧。