Random.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include "utils/Random.h"
  2. 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 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 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 Random::next(int min, int inclusiveMax) {
  29. return min + next() % (inclusiveMax - min + 1);
  30. }
  31. float Random::nextFloat() {
  32. static constexpr int bits = sizeof(int) * 6;
  33. static constexpr int mask = (1 << bits) - 1;
  34. return static_cast<float>(next() & mask) * (1.0f / (1.0f + mask));
  35. }
  36. float Random::nextFloat(float min, float exclusiveMax) {
  37. return min + nextFloat() * (exclusiveMax - min);
  38. }