Lets make a simpler rand():
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
constexpr int N = 5;
int wheel[N] {7, 2, 4, 9, 5};
int current = 0;
void srand( int pos ) {
current = pos % N;
}
int rand() {
int result = wheel[current];
++current;
current %= N; // current is always in [0..N)
return result;
}
|
If we call our rand() 4 times, then we will get {7, 2, 4, 9}
If we call srand(2) and then rand() 4 times, then we will get {4, 9, 5, 7}
If we call srand(time(0)) before each call to rand() and the time(0) returns 3 every time because our program is fast, then we will get {9, 9, 9, 9}
The "wheel" behind the C Standard Library's rand() is larger, but:
1 2 3 4 5 6 7
|
void function() {
srand((unsigned int)time(0));
infoGroupOne = rand() % 34;
infoGroupTwo = rand() % 34;
extraInfoOne = rand() % 5;
extraInfoTwo = rand() % 5;
}
|
... will get exact same four consecutive numbers from the "wheel" on every call of the 'function' (unless calls are far from each other in time).
Easy to test too:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <cstdlib>
#include <ctime>
void function() {
srand((unsigned int)time(0));
int a = rand() % 34;
int b = rand() % 34;
int c = rand() % 5;
int d = rand() % 5;
std::cout << a << ' ' << b << ' ' << c << ' ' << d << '\n';
}
int main ( ) {
for ( int i = 0 ; i < 10 ; ++i ) {
function();
}
}
|
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1
4 15 4 1 |
vs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <cstdlib>
#include <ctime>
void function() {
int a = rand() % 34;
int b = rand() % 34;
int c = rand() % 5;
int d = rand() % 5;
std::cout << a << ' ' << b << ' ' << c << ' ' << d << '\n';
}
int main ( ) {
srand((unsigned int)time(0));
for ( int i = 0 ; i < 10 ; ++i ) {
function();
}
}
|
24 22 1 0
19 27 1 3
5 13 1 2
26 25 0 2
9 29 2 0
0 31 1 2
14 2 0 1
28 30 3 0
18 13 0 1
6 23 2 0 |
As said, if you are about to learn C++, then do learn the use of
<random>
and skip the
<cstdlib>
for now.
See:
http://www.cplusplus.com/reference/random/