Hello again! In this video, we are going to look at random number algorithms.
In fact, there is only one random number algorithm in the library, which is shuffle().
And this will take a iterator range and put the elements into random order. So we pass it the iterator
range and a random number engine.
And this will do the stuff we saw before: it will use a uniform distribution to get the random numbers.
This will give "perfect shuffling", so-called, which means that all the permutations of the elements are
equally likely.
There was also an algorithm called random_shuffle().
This used rand() and it is deprecated.
I think actually it has now been removed.
So here is our vector. Here is our random number engine. Here is our call to shuffle(), and here is our shuffled vector.
OK.
There is one other thing I want to mention, which is the Bernoulli distribution.
So we have the uniform distribution, which will give a range of integers or reals, which are all equally
probable. With the Bernoulli distribution, we get Booleans.
So all the random numbers are scaled to give
either 1 or 0. True or false.
And this works the same way.
So we have a Bernoulli distribution object, and we pass the random number engine to it, and that will return
a random number, or a random Boolean.
So this is very useful if you want to make decisions which are 50-50. You know, equivalent to tossing
a coin.
Okay, so let's see how things are going in my kingdom, today.
"Your subjects are grateful for your wise and benevolent rule". And so they should be!
As this is rather a short video, I thought it was worth having a look at how the shuffle algorithm is
implemented.
The basic idea is that you take an elements and then pick another element at random and then swap the
two.
So you have a loop where you go through, and you swap each element with another one, which is chosen at
random.
So here is this code.
Here is my attempt at implementing it.
So we have our loop in which we swap the elements, so we iterate over each element and we choose
another element at random.
So we are going to use a random number as the index of the element that we are swapping it with.
We use the uniform_int_distribution, with ints.
This is going to generate an index, so we need to make sure it is within range.
We do not want any out of bounds access errors.
So the range we need is from 0 to size() minus one, the number of elements minus one.
And then we just loop over all the elements and swap them.
Okay, so there we are.
Our vector is shuffeld. The real implementation is going to be a templated function, of course,
and it will have some code to decide whether to use the real or integer version of uniform distribution.
The mathematics might be a bit more sophisticated. But, anyway, this will give you an idea of what
it does.
Okay, so that is it for this video.
I will see you next time.
Until then, keep coding!