dimanche 23 juin 2019

How can I do "weighted" random number generation that favors some numbers over others, depending on user input?

First, I believe this is also maths based, so mods, if this is not the right place to address such a question, feel free to migrate it to a proper place. I am asking here, because I want this problem to be implemented in programming, specifically in c++.

Suppose the following scenario: - I want to RNG a number between 0 and 8 - there is an extra input taking in factor to the number being generated, to give better odds to certain numbers in this way (I'll try to be as clear as I can) :

If the user inputs '0', the number to be generated will have the following chance to come out:

'0' - weight of 5,
'1' - weight of 4,
'2' - weight of 3,
'3' - weight of 2,
'4' - weight of 1,
'5' - weight of 0,
'6' - weight of 0,
'7' - weight of 0,
'8' - weight of 0,

So that the chance of getting a random '0' is 5 times bigger than getting a '4', and it's zero chance to get '5', '6', '7' and '8'.

If the user inputs a '4', then the weights are as follow:

'0' - weight of 1,
'1' - weight of 2,
'2' - weight of 3,
'3' - weight of 4,
'4' - weight of 5,
'5' - weight of 4,
'6' - weight of 3,
'7' - weight of 2,
'8' - weight of 1

In this case, all the numbers have a chance to come out, but favoring the number '4' to be generated. Also, numbers '3' and '5' have the same chance of coming out, but yet, less probable than the number '4'.

And so on.

This can be translated into a weight table as the next picture shows:

Table of Weights image

Considering that I made myself clear (if not, please tell me! I'll try to explain it in a better way) about the problem, how can the solution to this problem be designed?

I am tagging c++ because that's the language I am learning, but this can be applied to any language in general.

Best regards!




Aucun commentaire:

Enregistrer un commentaire