CRandomGenerator.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. typedef std::mt19937 TGenerator;
  12. typedef std::uniform_int_distribution<int> TIntDist;
  13. typedef std::uniform_real_distribution<double> TRealDist;
  14. typedef std::function<int()> TRandI;
  15. typedef std::function<double()> TRand;
  16. /// The random generator randomly generates integers and real numbers("doubles") between
  17. /// a given range. This is a header only class and mainly a wrapper for
  18. /// convenient usage of the boost random API.
  19. class CRandomGenerator
  20. {
  21. public:
  22. /// Seeds the generator with the current time by default.
  23. CRandomGenerator()
  24. {
  25. gen.seed(std::time(nullptr));
  26. }
  27. void seed(int value)
  28. {
  29. gen.seed(value);
  30. }
  31. /// Generate several integer numbers within the same range.
  32. /// e.g.: auto a = gen.getRangeI(0,10); a(); a(); a();
  33. TRandI getRangeI(int lower, int upper)
  34. {
  35. return boost::bind(TIntDist(lower, upper), gen);
  36. }
  37. int getInteger(int lower, int upper)
  38. {
  39. return getRangeI(lower, upper)();
  40. }
  41. /// Generate several double/real numbers within the same range.
  42. /// e.g.: auto a = gen.getRangeI(0,10); a(); a(); a();
  43. TRand getRange(double lower, double upper)
  44. {
  45. return boost::bind(TRealDist(lower, upper), gen);
  46. }
  47. double getDouble(double lower, double upper)
  48. {
  49. return getRange(lower, upper)();
  50. }
  51. private:
  52. TGenerator gen;
  53. };