我正在主持一场 AI 竞赛,并且有一个随机机器人可以选择随机的可能值。
机器人有 2 个导出函数:Init(_seed) 和 MakeMove()
为了玩完全相同的游戏,主机为每个机器人定义了种子值。并将其传递给 Init 函数。
random bot的Init函数有一个srand(_seed)函数调用。 random bot的MakeMove函数有一个rand()函数调用。
现在的问题是,加载2个机器人后,每个游戏应该是相同的,种子值相同,但它们是不同的。
据我所知,srand 应该按模块/线程存储它的值,而不是共享它。
我进行了测试并创建了一个函数 mysrand 和 myrand,它们分别不通过调用 srand 和 rand 导出。
我用 mysrand 和 myrand 替换了导出函数中的 srand 和 rand ...它起作用了...
我知道为什么会这样,但不确定...
那么为什么会发生这种情况以及如何避免这种情况,因为我希望参赛者在导出的函数中使用他们想要的任何函数(不想使用我的代理函数)。
谢谢。
我使用的是 windows,编译器:gcc、visual C++、borland C++ builder
最佳答案
如果你想获得一致的行为 <random>
图书馆可能是更好的选择。您可以控制 RNG 状态的存储位置,并且引擎可以在不同的实现中产生相同的值(尽管标准分布不需要在不同的实现中产生相同的输出)。
#include <random>
#include <iterator>
#include <algorithm>
#include <iostream>
int main() {
std::mt19937 eng;
std::generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&] {
// A simple example distribution function; not intended for real use.
return static_cast<int>(eng()/static_cast<double>(eng.max() + 1ull) * 20.0) + 1;
});
}
这应该在所有实现上输出以下内容:
17 3 19 17 3 20 19 5 13 7
如果您只需要在一个实现中而不是在实现之间保持一致的行为,那么您可以使用标准分布,并且您仍然可以控制 RNG 的状态。
#include <random>
#include <iterator>
#include <algorithm>
#include <iostream>
int main() {
std::mt19937 eng;
std::uniform_int_distribution<> dist(1,20);
std::generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&] { return dist(eng); });
}
标准发行版比您自己编写的发行版更受欢迎。
关于C++ srand,DLL 中的 rand 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966363/