@@ -11,6 +11,7 @@ namespace AI {
1111
1212std::minstd_rand& getRandomGenerator ();
1313
14+ // Return a random value (min and max are included)
1415template <typename T>
1516T randomValue (T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max())
1617{
@@ -20,22 +21,28 @@ T randomValue(T min = std::numeric_limits<T>::min(), T max = std::numeric_limits
2021// Return a random bool:
2122// random() ... will return true|false with 50% chance each
2223// random(15) ... will return true in 1/15 of the cases
23- inline bool random (unsigned total = 1u )
24+ // random(20, 5) ... will return true in 5 out of 20 cases, i.e. a probability of 25%. Sames as random(4, 1)
25+ inline bool random (unsigned total = 2u , unsigned chance = 1u )
2426{
25- return helpers::randomValue (getRandomGenerator (), 0u , total) == 0u ;
27+ RTTR_Assert (total > 0u );
28+ return (chance >= total) || randomValue (1u , total) <= chance;
2629}
2730
28- // random(20, 5) ... will return true in ~3/4 of the cases (random(20) > 5)
29- inline bool random ( unsigned total, unsigned chance )
31+ template < typename ContainerT>
32+ inline unsigned randomIndex ( const ContainerT& container )
3033{
31- return helpers::randomValue (getRandomGenerator (), 0u , total) > chance;
34+ RTTR_Assert (!container.empty ());
35+ return randomValue (0u , static_cast <unsigned >(container.size ()) - 1u );
3236}
3337
3438template <typename ContainerT>
35- inline unsigned randomIndex (const ContainerT& container)
39+ inline auto randomElement (const ContainerT& container)
3640{
3741 RTTR_Assert (!container.empty ());
38- return helpers::randomValue (getRandomGenerator (), 0u , static_cast <unsigned >(container.size ()) - 1u );
42+ auto it = container.begin ();
43+ if (container.size () > 1u )
44+ std::advance (it, randomIndex (container));
45+ return *it;
3946}
4047
4148} // namespace AI
0 commit comments