Write a one-liner function to return a random integer with decreasing chances as it gets higher

53 Views Asked by At

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!

1

There are 1 best solutions below

0
On

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

import numpy as np
draw = np.random.choice(np.arange(1, 5), size=1,p=np.arange(4, 0, -1)/np.sum(np.arange(4, 0, -1)))

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$.