c++ - 在C++中生成随机非重复数数组

标签 c++ arrays random dynamically-generated

我需要在 C++ 中生成随机非重复数字数组,在这部分代码中,我使用 srand 函数生成随机数,但有些数字是重复的。主要任务是为彩票生成随机数,所以我需要生成数字直到golden number,标记为int golden。

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
{
  int golden = 31;
  int i = 0;
  int array[35];

 srand((unsigned)time(0));
    while(i != golden){
        array[i] = (rand()%75)+1;
        cout << array[i] << endl;
        i++;
}
 }

最佳答案

一种策略是用从 1 到 75 的数字填充一个数组,然后使用 std::random_shuffle()在上面。然后,您可以从数组中读取数字,直到找到黄金数字。

关于c++ - 在C++中生成随机非重复数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878202/

相关文章:

PHP修复数组中的数字键

python - 在python中生成一个范围内的N个正整数加起来等于总数

java - 将背景图像更改为随机

c++ - GLFW - 在不使用循环的情况下保持窗口

c++ - cuBLAS 矩阵求逆比 MATLAB 慢得多

python - 从 numpy 中的一维数组创建方形 nxn 矩阵的最快方法

algorithm - 将随机范围从 1-5 扩展到 1-7

c++ - 正确格式化有错误的数字 (C++)

c++ - 使用标准 C++ wifstream 读取 UTF-8 文本并转换为 UTF-16

java - 如何处理java.lang.ArrayIndexOutOfBoundsException?