简体   繁体   English

std :: mt19937 mersenne twister分布与非重复值

[英]std::mt19937 mersenne twister distribution with non repeating values

I'd like to use the std::mt19937 random number generator to produce a list of numbers between 0 and 255. "Once a number has been chosen, it should not appear again in the set." 我想使用std :: mt19937随机数生成器生成0到255之间的数字列表。“一旦选择了数字,它就不应再出现在集合中。” - it's this bit I don't know how to do. - 这就是我不知道该怎么办。 The mathematical term for this escapes me(!) 这个数学术语逃脱了我(!)

std::mt19937                        twister;
std::uniform_int_distribution<int>  distribution;

twister.seed(91210);
distribution = std::uniform_int_distribution<int>(0,255);

std::vector vNumbers;
vNumbers.resize(256);

for( int n = 0; n < 256; ++ n )
    vNumbers[n] = distribution(twister);

There's algorithms for that: 有算法:

// fill a vector ith [0..255]:
std::vector<int> vNumbers(256);
std::iota(vNumbers.begin(), vNumbers.end(), 0);

// shuffle it
std::random_shuffle(vNumbers.begin(), vNumbers.end());

// done

With C++11 you can pass in your own generator for the RNG: (see also comments) 使用C ++ 11,您可以为RNG传入自己的生成器:(另请参阅注释)

std::shuffle(vNumbers.begin(), vNumbers.end(), twister);

Or you could roll your own (google Fisher-Yates, or see Knuth) 或者你可以自己推(谷歌Fisher-Yates,或看看Knuth)


Of course the iota can be replaced by te following 当然, iota可以替换为te以下

for (int i=0; i<256; ++i) vNumbers[i] = i;

You could use std::set instead of std::vector , as it will ensure you have no duplicates. 您可以使用std::set而不是std::vector ,因为它将确保您没有重复项。 Just loop until the size of the set is the number of value you want. 只需循环,直到集合的大小是您想要的值的数量。


Since it seems you want one of each number in just a random order, you don't really need to generate random numbers, just generate a sequence from 0 to 255, and then randomly shuffle them. 由于您似乎只需要随机顺序中的每个数字中的一个,因此您不需要生成随机数,只需生成0到255之间的序列,然后随机随机播放它们。

This can easily be done with some standard algorithms , like std::iota and std::random_shuffle : 这可以通过一些标准算法轻松完成,例如std::iotastd::random_shuffle

std::vector<int> values{256};
std::iota(values.begin(), values.end(), 0);
std::random_shuffle(values.begin(), values.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM