-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomNumberGeneration.cpp
54 lines (45 loc) · 2.22 KB
/
RandomNumberGeneration.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/***********************************************************************************************************************
Author: Francesca Nannizzi
Contact: [email protected]
Distributed March 2013
************************************************************************************************************************
This program demonstrates the use of srand() and rand() to generate pseudo-random numbers.
srand( unsigned int seed ) allows you to seed the rand() function with any unsigned integer value. Actually, if you seed with the same number twice, you'll see the same values repeated. By default, rand() is seeded with 1.
The function time() simply returns the current calendar time. Using srand( time(NULL) ) shouldn't give you the same results as an unseeded rand(), unless the current calendar time is precisely 1 (I believe the beginning of "time" for time() is January 1st, 1970). As I'm writing this, the time according to time(NULL) is 1347871596. If you haven't learned about pointers yet, all you need to know is that NULL refers to a NULL or nonexistent pointer. If you give time() a parameter other than NULL, it stores the current time in the object referred to by that parameter. We don't need to store the time to generate random numbers, so using time(NULL) works just fine.
This example prints 10 numbers generated by:
unseeded rand(),
rand() seeded with time(NULL),
rand() seeded with 1 (notice that the numbers match those generated by unseeded rand() ),
rand() seeded with 2.
***********************************************************************************************************************/
#include <iostream>
#include <time.h>
using namespace std;
int main () {
int num;
cout << "Unseeded" << endl;
for(int i = 0; i < 10; i++){
num = rand() % 50;
cout << num << endl;
}
cout << "Seeded with time(NULL)" << endl;
cout << "Current time: " << time(NULL) << endl;
srand(time(NULL));
for(int i = 0; i < 10; i++){
num = rand() % 50;
cout << num << endl;
}
cout << "Seeded with 1" << endl;
srand(1);
for(int i = 0; i < 10; i++){
num = rand() % 50;
cout << num << endl;
}
cout << "Seeded with 2" << endl;
srand(2);
for(int i = 0; i < 10; i++){
num = rand() % 50;
cout << num << endl;
}
return 0;
}