Pages

25/10/2019

[C++] Good random initialization and generator

While playing with the Rock, Paper, Scissors game, I had to pick a random move from three possible values for the AI. First attempt was:

 #include <ctime>  
   
 srand(time(NULL));  
   
 int move = rand() % 3;  


But I noticed that playing many short games (3 to 5 rounds) in quick succession would yield a fairly common pattern where the AI move would not change often enough.

So I found there is a better way to do so:

 #include <random>  
   
 std::random_device r;  
 std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};  
 std::mt19937 eng(seed);  
 //only 3 possible moves  
 std::uniform_int_distribution<> dist{0,2};  
   
 int move = dist(eng);  

No comments:

Post a Comment

With great power comes great responsibility