-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrandgen.h
98 lines (82 loc) · 2.78 KB
/
randgen.h
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#ifndef _RANDGEN_H
#define _RANDGEN_H
#include <ctime> // for time()
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <climits> // for INT_MAX
// designed for implementation-independent randomization
// if all system-dependent calls included in this class, then
// other classes can make use of this class in independent manner
// all random numbers are uniformly distributed in given range
//
// RandGen() --- constructor sets seed of random # generator
// once per program, not per class/object
//
// RandInt(int max)
// RandInt(int low,int max) - return random integer in range [0..max)
// when one parameter used, [low..max] when
// two parameters used
//
// examples: rnd.RandInt(6) is random integer [0..5] or [0..6)
// rnd.RandInt(3,10) is random integer [3..10]
// rnd.RandInt() is random integer [0..INT_MAX)
//
// RandReal() -- returns random double in range [0..1)
// RandReal(double low, double max) -- random double in range [low..max)
class RandGen
{
public:
RandGen(); // set seed for all instances
int RandInt(int max = INT_MAX); // returns int in [0..max)
int RandInt(int low, int max); // returns int in [low..max]
double RandReal(); // returns double in [0..1)
double RandReal(double low, double max); // range [low..max]
static void SetSeed(int seed); // static (per class) seed set
private:
static int ourInitialized; // for 'per-class' initialization
};
/*************** DEFINITIONS ****************/
int RandGen::ourInitialized = 0;
void RandGen::SetSeed(int seed)
// postcondition: system srand() used to initialize seed
// once per program (this is a static function)
{
if (0 == ourInitialized)
{ ourInitialized = 1; // only call srand once
srand(seed); // randomize
}
}
RandGen::RandGen()
// postcondition: system srand() used to initialize seed
// once per program
{
if (0 == ourInitialized)
{ ourInitialized = 1; // only call srand once
srand(unsigned(time(0))); // randomize
}
}
int RandGen::RandInt(int max)
// precondition: max > 0
// postcondition: returns int in [0..max)
{
return int(RandReal() * max);
}
int RandGen::RandInt(int low, int max)
// precondition: low <= max
// postcondition: returns int in [low..max]
{
return low + RandInt(max-low+1);
}
double RandGen::RandReal()
// postcondition: returns double in [0..1)
{
return rand() / (double(RAND_MAX) + 1);
}
double RandGen::RandReal(double low, double high)
{
double width = fabs(high-low);
double thelow = low < high ? low : high;
return RandReal()*width + thelow;
}
#endif