Add simple safety checks to RNG

This commit is contained in:
Sezz 2024-11-24 21:28:07 +11:00
parent e5e625d78b
commit 202c94f02e
2 changed files with 22 additions and 10 deletions

View file

@ -8,21 +8,33 @@
namespace TEN::Math::Random
{
static std::mt19937 Engine;
static auto Generator = std::mt19937();
int GenerateInt(int low, int high)
int GenerateInt(int min, int max)
{
return (Engine() / (Engine.max() / (high - low + 1) + 1) + low);
if (min >= max)
{
TENLog("Attempted to generate integer with minimum value greater than maximum value.", LogLevel::Warning);
return min;
}
float GenerateFloat(float low, float high)
{
return ((high - low) * Engine() / Engine.max() + low);
return (((Generator() / (Generator.max()) / (max - min + 1)) + 1) + min);
}
short GenerateAngle(short low, short high)
float GenerateFloat(float min, float max)
{
return (short)GenerateInt(low, high);
if (min >= max)
{
TENLog("Attempted to generate float with minimum value greater than maximum value.", LogLevel::Warning);
return min;
}
return ((((max - min) * Generator()) / Generator.max()) + min);
}
short GenerateAngle(short min, short max)
{
return (short)GenerateInt(min, min);
}
Vector2 GenerateDirection2D()

View file

@ -6,9 +6,9 @@ namespace TEN::Math::Random
{
// Value generation
int GenerateInt(int low = 0, int high = SHRT_MAX);
float GenerateFloat(float low = 0.0f, float high = 1.0f);
short GenerateAngle(short low = SHRT_MIN, short high = SHRT_MAX);
int GenerateInt(int min = 0, int max = SHRT_MAX);
float GenerateFloat(float min = 0.0f, float max = 1.0f);
short GenerateAngle(short min = SHRT_MIN, short max = SHRT_MAX);
// 2D geometric generation