Commit a9cbe751 authored by Alexander A. Maly's avatar Alexander A. Maly

Fixing randoms fot MinGW32

parent 7ff9ccf1
Pipeline #3526 failed with stages
in 1 minute and 59 seconds
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
#include <float.h> #include <float.h>
#include <time.h> #include <time.h>
#if !defined(APPLE) && !defined(USE_MINGW_TOOLCHAIN) #if !defined(APPLE) && !defined(__MINGW32__)
#include <random> #include <random>
static std::random_device rd; static std::random_device rd;
#endif #endif
...@@ -24,20 +24,23 @@ namespace Kumir ...@@ -24,20 +24,23 @@ namespace Kumir
void Random::init() void Random::init()
{ {
#if !defined(WIN32) #if defined(APPLE)
unsigned int seed = 0xDEADBEEF; unsigned int seed = 0xDEADBEEF;
FILE *urandom = fopen("/dev/urandom", "rb"); FILE *urandom = fopen("/dev/urandom", "rb");
fread(&seed, 1, sizeof(unsigned), urandom); fread(&seed, 1, sizeof(seed), urandom);
fclose(urandom); fclose(urandom);
srand(seed); srand(seed);
#elif defined(USE_MINGW_TOOLCHAIN) #elif defined(__MINGW32__)
srand(time(NULL)); struct timeval tv;
gettimeofday(&tv, 0);
unsigned int seed = tv.tv_sec * 1000 + tv.tv_usec / 1000;
srand(seed);
#endif #endif
} }
inline unsigned int Random::get_max() inline unsigned int Random::get_max()
{ {
#if !defined(WIN32) || defined(USE_MINGW_TOOLCHAIN) #if defined(APPLE) || defined(__MINGW32__)
return RAND_MAX; return RAND_MAX;
#else #else
return std::random_device::max() - std::random_device::min(); return std::random_device::max() - std::random_device::min();
...@@ -47,7 +50,7 @@ inline unsigned int Random::get_max() ...@@ -47,7 +50,7 @@ inline unsigned int Random::get_max()
unsigned int Random::get_sample() unsigned int Random::get_sample()
{ {
#if !defined(WIN32) || defined(USE_MINGW_TOOLCHAIN) #if defined(APPLE) || defined(__MINGW32__)
return rand(); return rand();
#else #else
return rd() - rd.min(); return rd() - rd.min();
...@@ -65,13 +68,14 @@ int Random::irand(int a, int b) ...@@ -65,13 +68,14 @@ int Random::irand(int a, int b)
return a; return a;
} }
unsigned int d = b - a + 1; unsigned int d = b - a, rd = get_max();
if (d == 0) { if ((d + 1 == 0) || (d > rd)) {
Core::abort(Core::fromUtf8("Неверный диапазон чисел")); Core::abort(Core::fromUtf8("Слишком широкий диапазон чисел"));
return 0; return 0;
} }
unsigned int rd = get_max(), rq = rd / d + (rd % d + 1) / d; d += 1;
unsigned int rq = rd / d + (rd % d + 1) / d;
assert (0 < rq); assert (0 < rq);
for (;;) { for (;;) {
...@@ -107,8 +111,8 @@ real Random::rrand(real a, real b) ...@@ -107,8 +111,8 @@ real Random::rrand(real a, real b)
real rd = get_max() + 1.0; real rd = get_max() + 1.0;
real v = get_sample() + 0.5; real v = get_sample() + 0.5;
real res = v / rd * d; real res = v / rd * d;
if (v < res) { if (d < res) {
res = v; res = d;
} }
return a + res; return a + res;
} }
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment