RNG.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * RNG.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. VCMI_LIB_NAMESPACE_BEGIN
  12. namespace vstd
  13. {
  14. using TRandI64 = std::function<int64_t()>;
  15. using TRand = std::function<double()>;
  16. class DLL_LINKAGE RNG
  17. {
  18. public:
  19. virtual ~RNG() = default;
  20. virtual TRandI64 getInt64Range(int64_t lower, int64_t upper) = 0;
  21. virtual TRand getDoubleRange(double lower, double upper) = 0;
  22. };
  23. }
  24. namespace RandomGeneratorUtil
  25. {
  26. template<typename Container>
  27. auto nextItem(const Container & container, vstd::RNG & rand) -> decltype(std::begin(container))
  28. {
  29. assert(!container.empty());
  30. return std::next(container.begin(), rand.getInt64Range(0, container.size() - 1)());
  31. }
  32. template<typename Container>
  33. auto nextItem(Container & container, vstd::RNG & rand) -> decltype(std::begin(container))
  34. {
  35. assert(!container.empty());
  36. return std::next(container.begin(), rand.getInt64Range(0, container.size() - 1)());
  37. }
  38. template<typename T>
  39. void randomShuffle(std::vector<T> & container, vstd::RNG & rand)
  40. {
  41. int64_t n = (container.end() - container.begin());
  42. for(int64_t i = n-1; i>0; --i)
  43. {
  44. std::swap(container.begin()[i],container.begin()[rand.getInt64Range(0, i)()]);
  45. }
  46. }
  47. }
  48. VCMI_LIB_NAMESPACE_END