C++随机代理移动是相同的

Ste*_*993 0 c++ random srand

我使用此函数生成数字0,1,2,3的随机排列,这些排列被转换为由游戏Tron的二维网格中的代理移动.

srand(time(nullptr));
vector<int> permutationMoves = { 0, 1, 2, 3 };
auto currentIndexCounter = permutationMoves.size();
for (auto iter = permutationMoves.rbegin(); iter != permutationMoves.rend();
     iter++, --currentIndexCounter) {
    int randomIndex = rand() % currentIndexCounter;
    if (*iter != permutationMoves.at(randomIndex)) {
        swap(permutationMoves.at(randomIndex), *iter);
    }
 }
Run Code Online (Sandbox Code Playgroud)

但是,我有两个问题:

  • 如果两个代理进行连续移动,则由于随机数取决于时间这一事实,它们会进行相同的移动.
  • 如果代理人在彼此之后进行多轮比赛,则两个代理人的移动与前一个游戏中的移动相同.所以最终网格总是相同的,并且在大多数情况下,1个代理最终赢得95%-100%的游戏.

所有帮助将非常感谢,谢谢!

amc*_*con 5

问题在于:

srand(time(nullptr));
Run Code Online (Sandbox Code Playgroud)

你每次都在重新种子.如果两次通话之间的时间很短,将产生相同的随机数.

删除该行并将其放在程序的开头.