如何在不重复一个数字多次的情况下生成一个范围之间的随机数

How can I generate a random number between a range without repeating a number more than once?

本文关键字:一个 情况下 范围 随机数 之间 数字      更新时间:2024-05-10

我想给对象的变量分配一个随机数,对于对象,随机数不应该与任何其他对象的变量匹配。

我已经编写了代码来生成一个范围之间的随机数,但它重复。所以,我想要一个解决方案。

根据您需要的索引范围,有多种解决方案。

如果它很小,只需生成所有值的矢量并对其进行洗牌

std::vector<size_t> indices(index_count);
std::iota(indices.begin(), indices.end(), 0);
std::random_shuffle(indices.begin(), indices.end()); // Or std::shuffle with custom RNG.

下一个解决方案是存储到目前为止生成的索引。

std::unordered_set<size_t> indices;
size_t generate(std::unordered_set<size_t>& indices) {
while (true) {
size_t index = ...; // Generate a possibly repeating index.
if (indices.insert(index).second) { // .insert(...).second checks whether the value is new in set.
return index;
}
}
}

最后一种解决方案是使用伪随机数生成器,该生成器可以在数学上证明不会重复(直到一些大量调用(。

相关文章: