RNG.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if(container.empty())
  30. throw std::runtime_error("Unable to select random item from empty container!");
  31. return std::next(container.begin(), rand.getInt64Range(0, container.size() - 1)());
  32. }
  33. template<typename Container>
  34. auto nextItem(Container & container, vstd::RNG & rand) -> decltype(std::begin(container))
  35. {
  36. if(container.empty())
  37. throw std::runtime_error("Unable to select random item from empty container!");
  38. return std::next(container.begin(), rand.getInt64Range(0, container.size() - 1)());
  39. }
  40. template<typename Container>
  41. size_t nextItemWeighted(Container & container, vstd::RNG & rand)
  42. {
  43. assert(!container.empty());
  44. int64_t totalWeight = std::accumulate(container.begin(), container.end(), 0);
  45. assert(totalWeight > 0);
  46. int64_t roll = rand.getInt64Range(0, totalWeight - 1)();
  47. for (size_t i = 0; i < container.size(); ++i)
  48. {
  49. roll -= container[i];
  50. if(roll < 0)
  51. return i;
  52. }
  53. return container.size() - 1;
  54. }
  55. template<typename T>
  56. void randomShuffle(std::vector<T> & container, vstd::RNG & rand)
  57. {
  58. int64_t n = (container.end() - container.begin());
  59. for(int64_t i = n-1; i>0; --i)
  60. {
  61. std::swap(container.begin()[i],container.begin()[rand.getInt64Range(0, i)()]);
  62. }
  63. }
  64. }
  65. VCMI_LIB_NAMESPACE_END