CRandomGenerator.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * CRandomGenerator.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. #include <boost/version.hpp>
  12. #include <boost/random/mersenne_twister.hpp>
  13. #if BOOST_VERSION >= 104700
  14. #include <boost/random/uniform_int_distribution.hpp>
  15. #include <boost/random/uniform_real_distribution.hpp>
  16. #else
  17. #include <boost/random/uniform_int.hpp>
  18. #include <boost/random/uniform_real.hpp>
  19. #endif
  20. #include <boost/random/variate_generator.hpp>
  21. typedef boost::mt19937 TGenerator;
  22. #if BOOST_VERSION >= 104700
  23. typedef boost::random::uniform_int_distribution<int> TIntDist;
  24. typedef boost::random::uniform_real_distribution<double> TRealDist;
  25. #else
  26. typedef boost::uniform_int<int> TIntDist;
  27. typedef boost::uniform_real<double> TRealDist;
  28. #endif
  29. typedef boost::variate_generator<TGenerator &, TIntDist> TRandI;
  30. typedef boost::variate_generator<TGenerator &, TRealDist> TRand;
  31. /// The random generator randomly generates integers and real numbers("doubles") between
  32. /// a given range. This is a header only class and mainly a wrapper for
  33. /// convenient usage of the boost random API.
  34. class CRandomGenerator
  35. {
  36. public:
  37. /// Seeds the generator with the current time by default.
  38. CRandomGenerator()
  39. {
  40. gen.seed(std::time(nullptr));
  41. }
  42. void seed(int value)
  43. {
  44. gen.seed(value);
  45. }
  46. /// Generate several integer numbers within the same range.
  47. /// e.g.: auto a = gen.getRangeI(0,10); a(); a(); a();
  48. TRandI getRangeI(int lower, int upper)
  49. {
  50. TIntDist range(lower, upper);
  51. return TRandI(gen, range);
  52. }
  53. int getInteger(int lower, int upper)
  54. {
  55. return getRangeI(lower, upper)();
  56. }
  57. /// Generate several double/real numbers within the same range.
  58. /// e.g.: auto a = gen.getRangeI(0,10); a(); a(); a();
  59. TRand getRange(double lower, double upper)
  60. {
  61. TRealDist range(lower, upper);
  62. return TRand(gen, range);
  63. }
  64. double getDouble(double lower, double upper)
  65. {
  66. return getRange(lower, upper)();
  67. }
  68. private:
  69. TGenerator gen;
  70. };