1) First you need a pseudo-random bit generator. This is some facility which generates a hard-to-predict sequence of bit.
Mersenne twister is a good tradeoff between randomness and speed. In older C++ or C you would use
rand() which is often uses subpar prng implementation.
1 2 3 4
|
#include <random>
//...
std::mt19937 rg(/* Read next section*/);
//...
|
2) Then you need to give it a start value. Best approach is to give some really unpredictable number, but finding source of it might be non-trivia. Best approach is to use
std::random_device, but it might be not supported (for example MinGW does not support it), so I would stop on
std::time(): old classic, which would be enough for your purpose.
1 2 3 4 5
|
#include <random>
#include <ctime>
//...
std::mt19937 rg(std::time(nullptr)); //Create random generator rg seeded with //...
}
|
3) Now you need something to transform sequence of random bits into number. That is distribution is for. as you need some number from diapason,
std::uniform_int_distribution is needed. It has the template parameter denoting return type and takes two values: min and max value of range it needs to generate:code]// Generate numbers from 1 to 100
// ↓ ↓
std::uniform_int_distribution< > dis(1, 100);
//Template argument is int ↑
//by default, so we do not need to explicitly mention it[/code]
Then you need to call distribution with generator as parameter:
dis(rg)
You can wrap it in function nicely:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <random> //Random stuff
#include <ctime> //std::time
#include <iostream>
int rand_num(int from, int to)
{
//Static is needed to seed our prng only once
//and all function calls will share generator
static std::mt19937 rg(std::time(nullptr));
//distribution is recreated each call because function might be called with different parameters
std::uniform_int_distribution<> dis(from, to);
return dis(rg); //return result of generation
}
int main()
{
for(int i =0; i < 20; ++i)
std::cout << rand_num(1, 100) << '\n';
}
|
46
93
96
11
73
91
20
82
45
83
85
19
36
24
3
66
15
93
85
70 |
http://ideone.com/3bYd9n