I am a computer programmer and I would like to write a simple formula that would return a random integer, but I’d like to decrease the chance of getting a value as it increases.
i.e., if I want to get an integer between 1 and 4, I would like this integer to have 4 chances to be 1, 3 chances to be 2, 2 chances to be 3 and 1 to be 4.
Intuitively, a way to write this program would be to do this:
var array = []
var currentCount = maxBound
for (i in 1…maxBound) {
var j = 0
while (j < currentCount) {
array.append(i)
j += 1
}
currentCount -= 1
}
// result would be a random element from array
I would like to find instead a one-liner way of writing it, supposed I have a function random(low,high) that returns any value between low and high.
Thank you for your help!
In Python (and probably in most other programming languages) there is the option that you can provide weights for a random generator. So in your case a simple python solution would be
This will draw an integer $1\leq m < 5$ while the probability is reversely distributed, i.e. $1$ has weight $4$, $2$ has weight $3$ and so on. The division is necessary so that the sum of all probabilities is exactly $1$.