Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

random.cpp 936B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*!
  2. * \file src/utils/random.cpp
  3. * \brief Random number generation
  4. *
  5. * \author xythobuz
  6. */
  7. #include <chrono>
  8. #include <map>
  9. #include <random>
  10. #include <utility>
  11. #include "global.h"
  12. #include "utils/random.h"
  13. static std::map<int, std::uniform_int_distribution<int>> distributions;
  14. static std::default_random_engine engine;
  15. static bool engineIsSeeded = false;
  16. int randomInteger(int max, int min) {
  17. if (max == min)
  18. return max;
  19. orAssertGreaterThan(max, min);
  20. if (!engineIsSeeded) {
  21. engine.seed(std::chrono::system_clock::now().time_since_epoch().count());
  22. engineIsSeeded = true;
  23. }
  24. int range = max - min;
  25. auto elem = distributions.find(range);
  26. if (elem == distributions.end()) {
  27. distributions[range] = std::uniform_int_distribution<int>(0, range);
  28. return distributions[range](engine) + min;
  29. } else {
  30. return std::get<1>(*elem)(engine) + min;
  31. }
  32. }