C++ inherits pretty much all the stuff in C, so I'll start with C as things are more basic there.
In C, there is a (pseudo) random number generator. All these PRNGs work by giving you the next number in a sequence. The start of the sequence is called the seed. The idea is you get a number back that's more or less unpredictable.
In C, you set the seed with
srand()
, and you get the next number in the sequence with
rand()
. The range of the number is the range of an
int
.
This C++ program uses the C PRNG to print the first 10 numbers from a given seed,
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
#include <stdlib.h>
int main()
{
srand(2015); // set the seed
for (int i = 0; i != 10; ++i)
std::cout << i << rand() << ' ';
std::cout << '\n';
}
|
It is common to use
srand(time(NULL));
to seed the PRNG with an unpredictable seed, so each time the program is run, it generates different numbers. Our program above will print the same numbers each time it is run.
If we want random numbers in the range of 0 - 5, so we can simulate throwing dice, we can use the mathematical modulus operation;
rand() % 6
.
If we want a number of values 0 or 1, so we can make a binary decision, we can use
rand() % 2
.
So, let's write a program that does exactly that; loops 10 times, printing a random left/right decision.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(nullptr)); // use an unpredictable seed
for (int i = 0; i != 10; ++i)
switch (rand() % 2)
{
case 0:
std::cout << "left" << std::endl;
break;
case 1:
std::cout << "right" << std::endl;
break;
default:
std::clog << "unexpected value from rand()" << std::endl;
}
}
|
Let us know if you don't understand any part of this.