C ++需要一种很好的技术来播种不使用time()的rand() [英] C++ need a good technique for seeding rand() that does not use time()

查看:144
本文介绍了C ++需要一种很好的技术来播种不使用time()的rand()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,可以启动许多客户端进程.这些是我用来测试具有400个连接的数量的许多玩家的游戏的AI游戏玩家.

I have a bash script that starts many client processes. These are AI game players that I'm using to test a game with many players, on the order of 400 connections.

我遇到的问题是AI播放器使用

The problem I'm having is that the AI player uses

srand( time(nullptr) );

但是,如果所有玩家都大约在同一时间开始比赛,他们将经常获得相同的time()值,这意味着他们都在相同的rand()序列上.

But if all the players start at approximately the same time, they will frequently receive the same time() value, which will mean that they are all on the same rand() sequence.

测试过程的一部分是确保如果许多客户端尝试同时连接,则服务器可以处理它.

Part of the testing process is to ensure that if lots of clients try to connect at approximately the same time, the server can handle it.

我曾经考虑使用类似的东西

I had considered using something like

srand( (int) this );

或类似,基于每个实例都有一个唯一的内存地址的想法.

Or similar, banking on the idea that each instance has a unique memory address.

还有另一种更好的方法吗?

Is there another better way?

推荐答案

如果希望再现结果,则使用随机数种子if和 only .这对于诸如地图生成之类的事情可能会很方便,在这种情况下,您希望地图随机化,但是希望它基于种子是可预测的随机性.

You use a random number seed if and only if you want reproducible results. This can be handy for things like map generation where you want the map to be randomized, but you want it to be predictably random based on the seed.

在大多数情况下,您不希望这样做,而是实际上需要随机数,而做到这一点的最佳方法是通过标准库生成器函数:

For most cases you don't want that, you want actually random numbers, and the best way to do that is through the Standard Library generator functions:

#include <random>

std::random_device rd;
std::map<int, int> hist;
std::uniform_int_distribution<int> dist(0, 5);

int random_die_roll = dist(rd);

在这种情况下,不需要种子或不建议使用种子. 随机设备"用于正确植入PRNG(伪随机数生成器),以确保结果不可预测.

No seed is required nor recommended in this case. The "random device" goes about seeding the PRNG (pseudo random number generator) properly to ensure unpredictable results.

再次,请勿使用srand(time(NULL)),因为它是初始化随机数的一种非常古老,非常糟糕的方法,并且具有很高的可预测性.在现代计算机上,旋转一百万个可能的种子以找到匹配的输出是简单的.

Again, DO NOT use srand(time(NULL)) because it's a very old, very bad method for initializing random numbers and it's highly predictable. Spinning through a million possible seeds to find matching output is trivial on modern computers.

这篇关于C ++需要一种很好的技术来播种不使用time()的rand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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