it is possible to specify your own random number generator to be used with std::random_shuffle() which accepts either of the following:

0) function object a.k.a functor

1) pointer to a function

this article will use the pointer to a function approach.

first we create a **unary** function that accepts an **appropriate** type of argument. by appropriate i mean a type which is convertible from std::iterator_traits::difference_type. we will be using the gsl_rng_uniform_int() function provided by the **GSL** library.

long unsigned myrng(long unsigned n)
{
return gsl_rng_uniform_int(rng, n);
}

notice how using myrng() we will be able to call a binary function using a unary interface. of course one must ensure that the variable **rng** is globally defined.

now that we have defined the unary function we need to define a pointer to this function, which we will pass to the

std::random_shuffle() function.

this is how we achieve that

long unsigned (*fp)(long unsigned) = myrng;

all the parts are in place for the final working program which is listed below:

#include <vector>
#include <gsl/gsl_rng.h>
// for gsl_rng_uniform_int
#include <algorithm>
// for random_shuffle
// global definition
gsl_rng * rng;
// unary function
long unsigned myrng(long unsigned n)
{
return gsl_rng_uniform_int(rng, n);
}
// pointer to unary function
long unsigned (*fp)(long unsigned) = myrng;
int main()
{
rng = gsl_rng_alloc(gsl_rng_default);
// [1.0, 2.0, 3.0, 4.0]
std::vector <double> a;
a.push_back(1.0);
a.push_back(2.0);
a.push_back(3.0);
a.push_back(4.0);
std::random_shuffle(a.begin(), a.end(), fp);
gsl_rng_free(rng);
return 0;
}

i m not too happy with this implementation as this uses a global definition of gsl_rng *. i will also try to write a version using functors at a later date.

### Like this:

Like Loading...

*Related*

## Leave a Reply