[英]Generate random long long C++
int
generator int
生成器I currently generate deterministic pseudo-random int
s using this code:我目前使用以下代码生成确定性伪随机int
:
#include <chrono>
#include <ctime>
#include <random>
#include <stdint.h>
const uint32_t CurrentTime = static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
std::mt19937 Mersenne = std::mt19937(static_cast<std::mt19937::result_type>(CurrentTime));
int Min = 3;
int Max = 6;
std::uniform_int_distribution<> Distribution(Min, Max-1);
int Result = Distribution(Mersenne);
There's two problems with this:这有两个问题:
Distribution
must be int
s. Distribution
的参数必须是int
s。Distribution(Mersenne)
is an int
. Distribution(Mersenne)
的结果是一个int
。How do I generate a random long long
instead of an int
, with the Min
and Max
parameters also being long long
s instead of int
s?如何生成随机long long
而不是int
, Min
和Max
参数也是long long
s 而不是int
s?
I'm creating a deterministic game (peer-to-peer architecture), and the large minimum-size of a long long
is needed as a sort of fixed-point number (since float
s can cause non-determinism).我正在创建一个确定性游戏(点对点架构),并且需要long long
的大最小尺寸作为一种定点数(因为float
s 可能导致不确定性)。
I won't accept answers that:我不会接受以下答案:
float
s or double
s使用float
或double
int
and casting it to a long long
建议生成一个int
并将其转换为long long
I would much prefer a solution from the standard library if there is one.如果有标准库中的解决方案,我会更喜欢它。
Ideally, the solution should be at least as efficient as my existing code on a 64-bit machine.理想情况下,该解决方案至少应该与我在 64 位机器上的现有代码一样高效。
the documentation says that the template parameter can be long long
文档说模板参数可以long long
long long Min = 3;
long long Max = 6;
std::uniform_int_distribution<long long> Distribution(Min, Max-1);
long long Result = Distribution(Mersenne);
Would that work for you?这对你有用吗?
#include <climits>
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd()); // Here you can use any seed to make it deterministic
std::uniform_int_distribution<long long> distrib(LLONG_MIN, LLONG_MAX);
for (int n = 0; n < 5; ++n)
std::cout << distrib(gen) << ' ';
std::cout << '\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.