生成范围内的随机数,不重复 [英] Generate random number in range without repetition

查看:189
本文介绍了生成范围内的随机数,不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++在给定范围内生成n个统一数字,而不重复。我想把它保存在数组(不是向量)。我发现一个代码,但它不允许生成数字没有重复。

I am using C++ to generate n uniform numbers in a given range without repeatition. I want to save it in array(not vector). I found a code but it does not allow to generate number without repetition.

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)

std::uniform_int_distribution<int> uni(0,10-1); // guaranteed unbiased
auto random_integer = uni(rng);

例如,我将在范围0-9中生成5个随机数,例如

For example, I will generate 5 random numbers in range 0-9 such as

1 0 3 8 6

这是我的代码

typedef unsigned int U32, *PU32;
U32 total_num = 5;
U32 *rndArray = new U32[total_num];
for (U32 i = 0; i < total_num; i++)
{
    std::random_device rd  // only used once to initialise (seed) engine
    std::mt19937 rng(rd());      
    std::uniform_int_distribution<int> uni(0,10-1);
    auto random_integer = uni(rng);
    rndArray[i] = random_integer ;
}

第二种方法,我使用的代码不允许重复。但是它不支持g ++(我在ubuntu中使用g ++)

Second way, I used the code bellow which allows without repetition. But it is not support in g++ (I am using g++ in ubuntu)

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
typedef unsigned int U32;
int main()
{        
    U32 total_num = 5;
    U32 *rndArray = new U32[total_num];
    std::random_device rd;
    std::mt19937 g(rd());
    std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::shuffle(v.begin(), v.end(), g);
    for (int i=0;i<5;i++)
    { 
        rndArray[i]=v[i];
        std::cout<< rndArray[i] << " ";
    }

    std::cout << "\n";
}


推荐答案

做这个。


  1. 如果随机数已存在于数组中,则生成另一个,直到找到一个没有被看到的数字。这很容易实现,但是理论上具有运行时间非常高的缺点。

  1. If the random number is already in the array, then generate another one until you find a number that has not been seen before. This is quick to implement but has the disadvantage of very high running time theoretically.

创建整个范围以数组开头,然后加扰。要获取k个数字,请获取加扰数组的前k个元素。

Create the entire range to begin with in an array and then scramble it. To get k numbers, obtain the first k elements of the scrambled array.

这篇关于生成范围内的随机数,不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆