Generating random non repeating number array in C++

时间秒杀一切 提交于 2019-12-02 04:03:35

问题


I need to generate random non repeating number array in C++, in this part of code I generate random numbers using, srand function, but some of the numbers are repeating. The main task is to generate random numbers for lottery ticket, so I need to generate numbers until golden number which is marked as 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:


One strategy is to populate an array with numbers from 1 to 75, and then use std::random_shuffle() on it. You can then read the numbers from the array until you hit the golden number.



来源:https://stackoverflow.com/questions/25878202/generating-random-non-repeating-number-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!