randomAPI.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. Copyright (C) 2025 Miguel Castillo
  3. Reviewed and adapted by David Forsgren Piuva
  4. This is free and unencumbered software released into the public domain.
  5. Anyone is free to copy, modify, publish, use, compile, sell, or
  6. distribute this software, either in source code form or as a compiled
  7. binary, for any purpose, commercial or non-commercial, and by any
  8. means.
  9. In jurisdictions that recognize copyright laws, the author or authors
  10. of this software dedicate any and all copyright interest in the
  11. software to the public domain. We make this dedication for the benefit
  12. of the public at large and to the detriment of our heirs and
  13. successors. We intend this dedication to be an overt act of
  14. relinquishment in perpetuity of all present and future rights to this
  15. software under copyright law.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  20. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  22. OTHER DEALINGS IN THE SOFTWARE.
  23. For more information, please refer to <https://unlicense.org>
  24. */
  25. #ifndef DFPSR_API_RANDOM
  26. #define DFPSR_API_RANDOM
  27. #include <cstdint>
  28. // A random generator.
  29. struct RandomGenerator {
  30. // The state makes sure that we get very different values each time the random generator is called.
  31. uint64_t impl_state[2] = {};
  32. // The indices rotate in a set of 68839 combination of indices using unique prime numbers.
  33. // 23 * 41 * 73 = 68839
  34. // This shakes the state with a limited source of true entropy repeated in a loop, because patterns are created each time a number is repeated.
  35. uint32_t impl_index[3] = {};
  36. // The nonce rotates in a set of 2⁶⁴ values to be absolutely sure that the state does not get stuck in a narrow loop.
  37. uint64_t impl_nonce = 7245416u;
  38. RandomGenerator() {}
  39. };
  40. // Returns a new random generator initialized by seed.
  41. RandomGenerator random_createGenerator(uint64_t seed);
  42. // Pre-condition: minimum <= maximum
  43. int32_t random_generate_range(RandomGenerator &generator, int32_t minimum, int32_t maximum);
  44. // Returns true for roughly perCentProbability times in a hundred.
  45. bool random_generate_probability(RandomGenerator &generator, int32_t perCentProbability);
  46. #endif