-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom_utils.h
More file actions
32 lines (26 loc) · 841 Bytes
/
random_utils.h
File metadata and controls
32 lines (26 loc) · 841 Bytes
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
/* random_utils.h
* A few utilities that use random number generators to perform actions.
*/
#ifndef RANDOM_UTILS_H
#define RANDOM_UTILS_H
#include<initializer_list>
#include<vector>
namespace CCCPP {
/* Randomly chooses one element of the vector and return it.
* This is a port of Orteil's choose.
*/
template<typename Vector, typename RNG>
auto choose(const Vector& vec, RNG& rng) {
auto index = static_cast<int>(rng() * vec.size());
return vec[index];
}
/* Explicit overload for initializer lists,
* because the standard explicitly excludes braced lists to argument type deduction.
* This way choose({1, 2, 3}, rng) works.
*/
template<typename T, typename RNG>
auto choose(const std::initializer_list<T>& list, RNG& rng) {
return choose<std::vector<T>>(list, rng);
}
} // namespace CCCPP
#endif // RANDOM_UTILS_H