Random.cpp 1.3 KB

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