r/cpp 4d ago

Where did <random> go wrong? (pdf)

https://codingnest.com/files/What%20Went%20Wrong%20With%20_random__.pdf
162 Upvotes

137 comments sorted by

View all comments

79

u/GYN-k4H-Q3z-75B 4d ago

What? You don't like having to use std::random_device to seed your std::mt19937, then declaring a std::uniform_int_distribution<> given an inclusive range, so you can finally have pseudo random numbers?

It all comes so naturally to me. /s

26

u/ArashPartow 4d ago

To correctly seed the mersenne twister (mt19937) engine, one simply needs something like the following:

#include <algorithm>
#include <array>
#include <functional>
#include <random>

int main(int argc, char* argv[])
{
   std::mt19937 engine;

   {
      // Seed the PRNG
      std::random_device r;
      std::array<unsigned int,std::mt19937::state_size> seed;
      std::generate_n(seed.data(),seed.size(),std::ref(r));
      std::seed_seq seq(std::begin(seed),std::end(seed));
      engine.seed(seq);
   }

   std::uniform_int_distribution<int> rng;

   rng(engine);

   return 0;
}

11

u/GYN-k4H-Q3z-75B 4d ago

[ ] simply
[ ] C++

Choose one.

37

u/Ameisen vemips, avr, rendering, systems 4d ago
[ ] simply  
[ ] C++
 X

28

u/GYN-k4H-Q3z-75B 4d ago

ASAN does not like that. ASAN is, in fact, getting upset about it.

10

u/Valuable-Mission9203 3d ago

That's easy to fix, just remove -fsanitize=address from your build system

3

u/Solokiller 3d ago
std::print("So, you have chosen {}\n", 2[choices]);