C++编写生成不重复的随机数代码
2019/7/10 23:09:14
本文主要是介绍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种方法均可实现生成不重复的随机数,具体的效率如何,小伙伴们自己测试下吧。
这篇关于C++编写生成不重复的随机数代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享