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!
lowandhighvalues equal to - say - $15$ and $19$ the probability of getting in order respectively $15,16,17,18,19$ should be proportional to $19,18,17,16,15$? (Or to $5,4,3,2,1$? Or to something else?) Any programming language is accepted, including pseudocode? Or there are some special preferences? May the solution already involve a random number generator (e.g. of a random number between zero and one) - or the one-liner should do the job from the scratch? Please mention some more details, maybe even the special purpose for the question and the range to be used, too. – dan_fulea Apr 04 '23 at 12:19