手机
当前位置:查字典教程网 >编程开发 >C语言 >C++编写生成不重复的随机数代码
C++编写生成不重复的随机数代码
摘要:C++编写生成不重复的随机数代码vectorgetRandom(inttotal){srand((int)time(NULL));std::...

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种方法均可实现生成不重复的随机数,具体的效率如何,小伙伴们自己测试下吧。

【C++编写生成不重复的随机数代码】相关文章:

8皇后问题的解法实例代码

C 二分查找 递归与非递归的实现代码

C语言中字符串和数字的相互转换实现代码

解决C++中重定义的方法总结

基于条件变量的消息队列 说明介绍

C/C++回调函数介绍

用C++实现一个链式栈的实例代码

C++生成dll和调用dll的方法实例

C/C++实现矩阵的转置(示例代码)

用C++实现队列的程序代码

精品推荐
分类导航