diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2024-03-01 15:00:32 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2024-03-01 15:00:32 +0100 |
commit | bd7637248c6ada567537392d3c69541c632e1c56 (patch) | |
tree | f4160671a920b05fecd7eb45442466b4fa7371ca /core/math/random_pcg.cpp | |
parent | d8cfc5e1c8f5d72bc21d42945aeab01bea508fa3 (diff) | |
parent | 88df5ea8acd423f2213441d84f2e0f9cd0280552 (diff) | |
download | redot-engine-bd7637248c6ada567537392d3c69541c632e1c56.tar.gz |
Merge pull request #88883 from joaoh82/add-weighted-random-method
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; } |