Random.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "core/utils/Random.hpp"
  2. Core::Random::Random(Seed seed) : index(0) {
  3. for(int i = 0; i < N; i++) {
  4. data[i] = seed;
  5. seed = seed * 7 + 31;
  6. }
  7. }
  8. void Core::Random::update() {
  9. static const Seed map[2] = {0, 0x8EBFD028};
  10. for(int i = 0; i < N - M; i++) {
  11. data[i] = data[i + M] ^ (data[i] >> 1) ^ map[data[i] & 1];
  12. }
  13. for(int i = N - M; i < N; i++) {
  14. data[i] = data[i + (M - N)] ^ (data[i] >> 1) ^ map[data[i] & 1];
  15. }
  16. index = 0;
  17. }
  18. int Core::Random::next() {
  19. if(index >= N) {
  20. update();
  21. }
  22. Seed r = data[index++];
  23. r ^= (r << 7) & 0x2B5B2500;
  24. r ^= (r << 15) & 0xDB8B0000;
  25. r ^= (r >> 16);
  26. return static_cast<int>(r >> 1);
  27. }
  28. int Core::Random::next(int min, int inclusiveMax) {
  29. return min + next() % (inclusiveMax - min + 1);
  30. }
  31. bool Core::Random::nextBool() {
  32. return next() & 1;
  33. }
  34. float Core::Random::nextFloat() {
  35. static constexpr i32 m = 0x7FFFFFFF;
  36. float f = static_cast<float>(next() & m) * (1.0f / static_cast<float>(m));
  37. return f >= 1.0f ? nextFloat() : f;
  38. }
  39. float Core::Random::nextFloat(float min, float exclusiveMax) {
  40. return min + nextFloat() * (exclusiveMax - min);
  41. }