diff options
author | João Henrique Machado Silva <joaoh82@gmail.com> | 2024-02-29 13:29:53 +0100 |
---|---|---|
committer | João Henrique Machado Silva <joaoh82@gmail.com> | 2024-02-29 13:29:53 +0100 |
commit | 88df5ea8acd423f2213441d84f2e0f9cd0280552 (patch) | |
tree | aad4c7c8f31394bedb5f67b0185d7e8033ecf64b /core/math/random_pcg.cpp | |
parent | bb6b06c81343073f10cbbd2af515cf0dac1e6549 (diff) | |
download | redot-engine-88df5ea8acd423f2213441d84f2e0f9cd0280552.tar.gz |
Add RandomNumberGenerator::rand_weighted method
Diffstat (limited to 'core/math/random_pcg.cpp')
-rw-r--r-- | core/math/random_pcg.cpp | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/core/math/random_pcg.cpp b/core/math/random_pcg.cpp index 45a9285ddd..e754a34271 100644 --- a/core/math/random_pcg.cpp +++ b/core/math/random_pcg.cpp @@ -31,6 +31,7 @@ #include "random_pcg.h" #include "core/os/os.h" +#include "core/templates/vector.h" RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) : pcg(), @@ -42,6 +43,26 @@ void RandomPCG::randomize() { seed(((uint64_t)OS::get_singleton()->get_unix_time() + OS::get_singleton()->get_ticks_usec()) * pcg.state + PCG_DEFAULT_INC_64); } +int RandomPCG::rand_weighted(const Vector<float> &p_weights) { + ERR_FAIL_COND_V_MSG(p_weights.is_empty(), -1, "Weights array is empty."); + int64_t weights_size = p_weights.size(); + const float *weights = p_weights.ptr(); + float weights_sum = 0.0; + for (int64_t i = 0; i < weights_size; ++i) { + weights_sum += weights[i]; + } + + float remaining_distance = Math::randf() * weights_sum; + for (int64_t i = 0; i < weights_size; ++i) { + remaining_distance -= weights[i]; + if (remaining_distance < 0) { + return i; + } + } + + return -1; +} + double RandomPCG::random(double p_from, double p_to) { return randd() * (p_to - p_from) + p_from; } |