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

Commit

Permalink
Merge pull request #1485 from zach2good/get_random_element
Browse files Browse the repository at this point in the history
Add GetRandomElement helpers and cleanup tpzrand
  • Loading branch information
zach2good authored Nov 8, 2020
2 parents 36c0776 + b15a382 commit 72b91ac
Showing 1 changed file with 36 additions and 12 deletions.
48 changes: 36 additions & 12 deletions src/common/tpzrand.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ class tpzrand
mt().seed(seq);
}

/*Generates a random number in the half-open interval [min, max)
@param min
@param max
@returns result
*/
// Generates a random number in the half-open interval [min, max]
// @param min
// @param max
// @returns result
template <typename T>
static inline typename std::enable_if<std::is_integral<T>::value, T>::type
GetRandomNumber(T min, T max)
GetRandomNumber(T min, T max)
{
if (min == max - 1 || max == min)
{
Expand All @@ -37,7 +36,7 @@ class tpzrand

template<typename T>
static inline typename std::enable_if<std::is_floating_point<T>::value, T>::type
GetRandomNumber(T min, T max)
GetRandomNumber(T min, T max)
{
if (min == max)
{
Expand All @@ -47,14 +46,39 @@ class tpzrand
return dist(mt());
}

/*Generates a random number in the half-open interval [0, max)
@param min
@param max
@returns result
*/
// Generates a random number in the half-open interval [0, max)
// @param min
// @param max
// @returns result
template <typename T>
static inline T GetRandomNumber(T max)
{
return GetRandomNumber<T>(0, max);
}

// Gets a random element from the given stl-like container (container must have members: at() and size()).
// @param container
// @returns result
template <typename T> static inline typename T::value_type GetRandomElement(T* container)
{
// NOTE: the specialisation for integral types uses: dist(min, max - 1), so no need to offset container->size()
return container->at(GetRandomNumber<std::size_t>(0U, container->size()));
}

// Gets a random element from the given stl-like container (container must have members: at() and size()).
// @param container
// @returns result
template <typename T> static inline typename T::value_type GetRandomElement(T& container)
{
return GetRandomElement(&container);
}

// Gets a random element from the given initializer_list.
// @param initializer_list
// @returns result
template <typename T> static inline T GetRandomElement(std::initializer_list<T> list)
{
std::vector<T> container(list);
return GetRandomElement(container);
}
};

0 comments on commit 72b91ac

Please sign in to comment.