lundi 20 février 2023

How would I generate random numbers that satisfy a specific ratio in C++?

Consider this piece of contrived code in the context of generating trees for a game:


// Pretend there's some code somewhere that associates the 0-100 number to its corresponding size.
enum class TreeSize : uint32_t
{
    Small, // 0-9
    Medium, // 10-60
    Large,// 61-90
    ExtraLarge, // 91-100

};

// returns tree size
int GenerateTree()
{
    std::random_device rd;
    std::mt19937_64 mt(rd());
    std::uniform_int_distribution<int32_t> dist(0, 100);

   return dist(s_mt);
}

Let's say I want to generate 1000 trees, but bound to a specific ratio of tree sizes. For example:

  • Small trees: 15%
  • Medium trees: 30%
  • Large trees: 40%
  • Extra large trees: 15%

How would I do that? Is there something off the shelf that accomplishes this? Surely this is a problem many people have had to contend with before, yeah?




Aucun commentaire:

Enregistrer un commentaire