Generating random non repeating number array in C+

2019-07-15 13:50发布

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条回答
Summer. ? 凉城
2楼-- · 2019-07-15 14:08

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.

查看更多
登录 后发表回答