Provide a suite of procedures for random-number generation.
More...
Namespaces |
namespace | bdlb |
Detailed Description
- Outline
-
-
- Purpose:
- Provide a suite of procedures for random-number generation.
-
- Classes:
bdlb::Random | namespace for a suite of random-number generation procedures |
- See also:
- Component bdlb_pcgrandomgenerator
-
- Description:
- This component provides a utility
struct
, bdlb::Random
, that is a namespace for a suite of functions used to efficiently generate random numbers over a specific range of values. The seed (or current state) is maintained externally. Two variants of a 15-bit random number generator are provided: one has a single [in/out] seed parameter, which is first used then updated; the other takes the current seed as an [input] parameter, and stores a new seed in an [output] parameter. A third generator produces 32-bit random numbers employing the PCG algorithm.
-
- Usage:
- This section illustrates intended use of this component.
-
- Example 1: Simulating a Pair of Dice:
- This example shows how one might use
bdlb::Random
to create and use a class to simulate the roll of a single die in a game, such as craps, that uses dice.
- First, we define the
Die
class itself:
class Die {
int d_seed;
public:
Die(int initialSeed);
int roll();
};
inline
Die::Die(int initialSeed)
: d_seed(initialSeed)
{
}
int Die::roll()
{
int result;
do {
result = bdlb::Random::generate15(&d_seed) & 7;
} while (result > 5);
return result + 1;
}
Now, we can use our Dice
class to get the random numbers needed to simulate a game of craps. Note that the game of craps requires two dice.
- We can instantiate a single
Die
and role it twice, void rollOneDieTwice()
{
Die a(123);
int d1 = a.roll();
int d2 = a.roll();
cout << "d1 = " << d1 << ", d2 = " << d2 << endl;
}
Alternatively, we could create two instances of Die
, with separate initial seeds, and role each one once: void rollTwoDice()
{
Die a(123);
Die b(456);
int d1 = a.roll();
int d2 = b.roll();
cout << "d1 = " << d1 << ", d2 = " << d2 << endl;
}
Note that the specification of separate seeds is important to produce a proper distribution for our game. If we had shared the seed value each die would always produce the same sequence of values as the other. void shareSeed()
{
Die a(123);
Die b(123);
int d1 = a.roll();
int d2 = b.roll();
assert(d2 == d1);
}