-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathRandom.cpp
More file actions
72 lines (63 loc) · 1.88 KB
/
Random.cpp
File metadata and controls
72 lines (63 loc) · 1.88 KB
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
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Random.cpp
* Random number generator
* Copyright (C) 2012 Simon Newton
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#ifdef HAVE_RANDOM
#include <random>
#endif // HAVE_RANDOM
#include "ola/Clock.h"
#include "ola/math/Random.h"
namespace ola {
namespace math {
#ifdef HAVE_RANDOM
std::default_random_engine generator_;
#endif // HAVE_RANDOM
void InitRandom() {
Clock clock;
TimeStamp now;
clock.CurrentTime(&now);
uint64_t seed = (static_cast<uint64_t>(now.Microseconds()) << 32) +
static_cast<uint64_t>(getpid());
#ifdef HAVE_RANDOM
generator_.seed(seed);
#elif defined(_WIN32)
srand(seed);
#else
srandom(seed);
#endif // HAVE_RANDOM
}
int Random(int lower, int upper) {
#ifdef HAVE_RANDOM
std::uniform_int_distribution<int> distribution(lower, upper);
return distribution(generator_);
#elif defined(_WIN32)
return (lower +
(rand() % (upper - lower + 1))); // NOLINT(runtime/threadsafe_fn)
#else
return (lower + (random() % (upper - lower + 1)));
#endif // HAVE_RANDOM
}
} // namespace math
} // namespace ola