本文介绍了在C ++中生成随机非重复数字数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C ++中生成随机非重复数数组,在这部分代码中,我会使用srand函数生成随机数,但是其中一些是重复的.主要任务是为彩票生成随机数,因此我需要生成数字,直到标记为int golden的黄金编号.

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到75之间的数字填充数组,然后使用 std::random_shuffle() 就可以了.然后,您可以从数组中读取数字,直到您击中黄金数字为止.

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.

这篇关于在C ++中生成随机非重复数字数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:28