From b15a382f286143303f4237f19017f2d52c34c9b5 Mon Sep 17 00:00:00 2001 From: Zach Toogood Date: Sun, 8 Nov 2020 10:55:54 +0200 Subject: [PATCH] Add GetRandomElement helpers and cleanup tpzrand --- src/common/tpzrand.h | 48 +++++++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/src/common/tpzrand.h b/src/common/tpzrand.h index 24faac67c0e..165e193639d 100644 --- a/src/common/tpzrand.h +++ b/src/common/tpzrand.h @@ -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 static inline typename std::enable_if::value, T>::type - GetRandomNumber(T min, T max) + GetRandomNumber(T min, T max) { if (min == max - 1 || max == min) { @@ -37,7 +36,7 @@ class tpzrand template static inline typename std::enable_if::value, T>::type - GetRandomNumber(T min, T max) + GetRandomNumber(T min, T max) { if (min == max) { @@ -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 static inline T GetRandomNumber(T max) { return GetRandomNumber(0, max); } + + // Gets a random element from the given stl-like container (container must have members: at() and size()). + // @param container + // @returns result + template 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(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 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 static inline T GetRandomElement(std::initializer_list list) + { + std::vector container(list); + return GetRandomElement(container); + } };