Skip to content
This repository was archived by the owner on Dec 4, 2020. It is now read-only.

Commit 72b91ac

Browse files
authored
Merge pull request #1485 from zach2good/get_random_element
Add GetRandomElement helpers and cleanup tpzrand
2 parents 36c0776 + b15a382 commit 72b91ac

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

src/common/tpzrand.h

+36-12
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,13 @@ class tpzrand
1818
mt().seed(seq);
1919
}
2020

21-
/*Generates a random number in the half-open interval [min, max)
22-
@param min
23-
@param max
24-
@returns result
25-
*/
21+
// Generates a random number in the half-open interval [min, max]
22+
// @param min
23+
// @param max
24+
// @returns result
2625
template <typename T>
2726
static inline typename std::enable_if<std::is_integral<T>::value, T>::type
28-
GetRandomNumber(T min, T max)
27+
GetRandomNumber(T min, T max)
2928
{
3029
if (min == max - 1 || max == min)
3130
{
@@ -37,7 +36,7 @@ class tpzrand
3736

3837
template<typename T>
3938
static inline typename std::enable_if<std::is_floating_point<T>::value, T>::type
40-
GetRandomNumber(T min, T max)
39+
GetRandomNumber(T min, T max)
4140
{
4241
if (min == max)
4342
{
@@ -47,14 +46,39 @@ class tpzrand
4746
return dist(mt());
4847
}
4948

50-
/*Generates a random number in the half-open interval [0, max)
51-
@param min
52-
@param max
53-
@returns result
54-
*/
49+
// Generates a random number in the half-open interval [0, max)
50+
// @param min
51+
// @param max
52+
// @returns result
5553
template <typename T>
5654
static inline T GetRandomNumber(T max)
5755
{
5856
return GetRandomNumber<T>(0, max);
5957
}
58+
59+
// Gets a random element from the given stl-like container (container must have members: at() and size()).
60+
// @param container
61+
// @returns result
62+
template <typename T> static inline typename T::value_type GetRandomElement(T* container)
63+
{
64+
// NOTE: the specialisation for integral types uses: dist(min, max - 1), so no need to offset container->size()
65+
return container->at(GetRandomNumber<std::size_t>(0U, container->size()));
66+
}
67+
68+
// Gets a random element from the given stl-like container (container must have members: at() and size()).
69+
// @param container
70+
// @returns result
71+
template <typename T> static inline typename T::value_type GetRandomElement(T& container)
72+
{
73+
return GetRandomElement(&container);
74+
}
75+
76+
// Gets a random element from the given initializer_list.
77+
// @param initializer_list
78+
// @returns result
79+
template <typename T> static inline T GetRandomElement(std::initializer_list<T> list)
80+
{
81+
std::vector<T> container(list);
82+
return GetRandomElement(container);
83+
}
6084
};

0 commit comments

Comments
 (0)