Posted by: sureshamrita | August 27, 2011

random_shuffle with Boost generator

The C++ algorithm random_shuffle accepts a random number generator as the third argument. One advantage of using your own random number generator is that  you can seed it the way you want. The following code segment demonstrates how it can be done with boost random number generator.

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

boost::mt19937 generator(currentTimeNS());
boost::uniform_int<> uni_dist;
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomNumber(generator, uni_dist);

vector<int> v = {1,2,3,4,5,6,7,8,9,10};
random_shuffle(v.begin(), v.end(),randomNumber);

The function currentTimeNS() gives the current time in nanoseconds which is used as a seed. For an implementation of  currentTimeNS() function see this link.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: