Skip to content

Instantly share code, notes, and snippets.

@Cristy94
Created September 1, 2019 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cristy94/27b5c972b2e33e4b127acebe4eb371db to your computer and use it in GitHub Desktop.
Save Cristy94/27b5c972b2e33e4b127acebe4eb371db to your computer and use it in GitHub Desktop.
inline int round_positive_float(float f)
{
return static_cast〈int〉(f + 0.5f);
}
class ControlledRandom
{
float state = 1.0f;
int index = 0;
static constexpr float constant_to_multiply[101] =
{
1.0f,
0.999842823f, 0.999372184f, 0.99858737f, 0.997489989f, 0.996079504f, // 5%
0.994353354f, 0.992320299f, 0.989976823f, 0.987323165f, 0.984358072f, // 10%
0.98108995f, 0.977510273f, 0.973632514f, 0.969447076f, 0.964966297f, // 15%
0.960183799f, 0.955135703f, 0.949759007f, 0.94411546f, 0.93817538f, // 20%
0.931944132f, 0.925439596f, 0.918646991f, 0.91158092f, 0.904245615f, // 25%
0.896643937f, 0.888772905f, 0.880638301f, 0.872264326f, 0.863632858f, // 30%
0.854712844f, 0.845594227f, 0.836190343f, 0.826578021f, 0.816753447f, // 35%
0.806658566f, 0.796402514f, 0.785905063f, 0.775190175f, 0.764275074f, // 40%
0.753200769f, 0.741862416f, 0.730398834f, 0.71871227f, 0.706894219f, // 45%
0.694856822f, 0.68264246f, 0.670327544f, 0.657848954f, 0.645235062f, // 50%
0.6324597f, 0.619563162f, 0.606526911f, 0.593426645f, 0.580169916f, // 55%
0.566839218f, 0.553292334f, 0.539853752f, 0.526208699f, 0.512536764f, // 60%
0.498813927f, 0.485045046f, 0.471181333f, 0.457302243f, 0.443413943f, // 65%
0.429503262f, 0.415506482f, 0.401567012f, 0.38765198f, 0.373695225f, // 70%
0.359745115f, 0.345868856f, 0.331981093f, 0.31815201f, 0.304365695f, // 75%
0.290644556f, 0.277024776f, 0.263462812f, 0.249986023f, 0.236542806f, // 80%
0.223382816f, 0.210130796f, 0.197115764f, 0.184175551f, 0.171426639f, // 85%
0.158810839f, 0.146292359f, 0.133954003f, 0.121768393f, 0.109754287f, // 90%
0.0979399607f, 0.0863209665f, 0.0748278722f, 0.0635780841f, 0.0524956733f, // 95%
0.0415893458f, 0.0308760721f, 0.0203953665f, 0.0100950971f, //99%
-1.0f,
};
public:
explicit ControlledRandom(float odds)
{
if (odds ≤ 0.0f)
index = 0;
else if (odds ≥ 1.0f)
index = 100;
else
index = std::min(std::max(round_positive_float(odds * 100.0f), 1), 99);
}
template〈typename Randomness〉
bool random_success(Randomness & randomness)
{
state *= constant_to_multiply[index];
if (std::uniform_real_distribution〈float〉()(randomness) ≤ state)
return false;
state = 1.0f;
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment