Home >Backend Development >C++ >How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?
Weighted Random Number Generation
Choosing random numbers with specific probabilities is a common task in programming. Boost's random number generator provides a convenient way to select items with weighted probabilities.
Consider the scenario where you want to pick a random number between 1 and 3 with the following weights:
Algorithm
Boost does not have built-in functionality for weighted random number generation. However, there is a simple algorithm that can be applied:
Code Example
In Boost, using the random_device and mt19937 random number generator:
std::mt19937 rng(std::random_device{}()); int total_weight = 90 + 56 + 4; for (int i = 0; i < total_weight; i++) { int random_number = rng() % total_weight; int current_weight = 90; if (random_number < current_weight) { return 1; } current_weight += 56; if (random_number < current_weight) { return 2; } return 3; // Reached the end of the weights }
Optimizations
If weights rarely change and random picks are frequent, an optimization can be applied by storing the cumulative weight sum in each item. This allows for a more efficient binary search approach.
Additionally, if the number of items is unknown but the weights are known, reservoir sampling can be adapted for weighted random number generation.
The above is the detailed content of How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?. For more information, please follow other related articles on the PHP Chinese website!