如何使用伪随机数生成器生成一组特定的数字? [英] How can I generate a specific set of numbers using a pseudorandom number generator?

查看:117
本文介绍了如何使用伪随机数生成器生成一组特定的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很沮丧,因为我不知道自己的尝试是否可行.

I am frustrated because I do not know if what I am attempting is even possible.

让我们说我有一个无符号数字列表. 我想为某种伪随机数生成器算法创建一个种子,该算法可以生成该组特定的数字.

Lets say I have a list of unsigned numbers. I want to create a seed for a certain pseudorandom number generator algorithm that can generate that specific set of numbers.

创建种子时,我知道列表的长度以及最小/最大数字.

When creating the seed, I know the length of the list, and the minimum/maximum numbers.

这是我目前用于生成数字的算法(C ++):

Here is my current algorithm for generating numbers (C++):

unsigned short rng(unsigned short lowerBounds, unsigned short upperBounds){
    static unsigned short lim = (upperBounds - lowerBounds)+1;
    static unsigned short a = 1; //SEED
    a = a*2 % 32749;
    return (a % lim)+lowerBounds;
}

例如,我要输入数字{63,37,82,34,75}

So for example, I would have the numbers { 63, 37, 82, 34, 75}

我需要一个种子,以便在前5次运行中生成这些数字(我想顺序不重要)

I would need to have a seed that would generate those numbers in the first 5 runs (order doesnt matter i suppose)

简单来说,我想控制RNG生成的数字

In simpler terms, I want to control the numbers that an RNG generates

推荐答案

先编码

#include <random>
#include <iostream>

int f(int low, int high)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(low, high);

    return dis(gen);
}

std::uniform_int_distribution将以这种方式为您提供您范围内的随机数.如果您知道种子的长度,那么这就是您要做的

std::uniform_int_distribution will give you a random number in your range this way. If your seed is known as well as the length, here is what you do

std::vector<int> f(int low, int high, unsigned seed, int len)
{
    std::vector<int> ret; // RVO applies, no worries
    std::mt19937 gen(seed);
    std::uniform_int_distribution<> dis(low, high);

    for (int i(0); i<len; ++i) {
        ret.push_back(dis(gen));
    }
    return ret;
}

这篇关于如何使用伪随机数生成器生成一组特定的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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