Random.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <chrono>
  2. #include <iostream>
  3. #include "utils/Random.h"
  4. Random::Random(int seed) : index(0) {
  5. for(int i = 0; i < N; i++) {
  6. data[i] = seed;
  7. seed = seed * 7 + 31;
  8. }
  9. }
  10. Random::Random() : Random(std::chrono::steady_clock::now().time_since_epoch().count()) {
  11. }
  12. float Random::nextFloat() {
  13. static constexpr int bits = sizeof(int) * 6;
  14. static constexpr int mask = (1 << bits) - 1;
  15. return (next() & mask) * (1.0f / (1.0f + mask));
  16. }
  17. void Random::update() {
  18. static const int map[2] = {0, -1900031960};
  19. for(int i = 0; i < N - M; i++) {
  20. data[i] = data[i + M] ^ (data[i] >> 1) ^ map[data[i] & 1];
  21. }
  22. for(int i = N - M; i < N; i++) {
  23. data[i] = data[i + (M - N)] ^ (data[i] >> 1) ^ map[data[i] & 1];
  24. }
  25. index = 0;
  26. }
  27. int Random::next() {
  28. if(index >= N) {
  29. update();
  30. }
  31. int r = data[index++];
  32. r ^= (r << 7) & 0x2B5B2500;
  33. r ^= (r << 15) & 0xDB8B0000;
  34. r ^= (r >> 16);
  35. return r & static_cast<int> (-1u >> 1);
  36. }
  37. int Random::next(int min, int max) {
  38. return min + next() % (max - min + 1);
  39. }