0

I use this function to generate random permutations of the digits 0,1,2,3 which are translated to moves by agents in a 2-dimensional grid for the game 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);
    }
 }

However, I have two issues:

  • If two agents make consecutive moves they make the same move due to the fact that the random number is dependent on time.
  • If the agents play multiple rounds after each other, the moves of both agents are identical to the moves in the previous game. So eventually the grid is always the same and 1 agent ends up winning 95%-100% of the games in most cases.

All help will be highly appreciated, thanks!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Stefan1993
  • 193
  • 2
  • 2
  • 15

2 Answers2

5

The problem is in:

srand(time(nullptr));

You are reseting the seed every time. If the time between 2 calls is short, will generate same random numbers.

Remove that line and put it in the beginning of the program.

amchacon
  • 1,891
  • 1
  • 18
  • 29
3

rand() and srand are pseudo-random number generators, so you could generate random numbers the C++11 way.

std::random_device randomDevice;
std::mt19937 generator(randomDevice());
std::uniform_int_distribution<> distribution(1, 100);
int randNum = distribution(generator);

Make sure you #include <random>

BnBDim
  • 136
  • 5
  • I would never use `std::mt19937` in a real application. It is far too slow when there's [PRNGs with similar or better characteristics](http://www.pcg-random.org/) that run orders of magnitude faster. Or just stick with `rand()` for stuff where uneven randomness doesn't matter. – Cameron Sep 20 '16 at 16:41
  • 1
    Note mt19937 is also a pseudo-random number generator. – Martin York Sep 20 '16 at 17:24