1

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!

  • 2
    This probably belongs to stackoverflow? Or is there some mathematics-specific question that you want to ask? – Trebor Apr 04 '23 at 12:01
  • @Trebor The coding part belongs probably to SO, however the methodology and algorithm behind could be a good fit for here. – Surb Apr 04 '23 at 12:07
  • 1
    And in case of the low and high values 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

1 Answers1

0

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

LegNaiB
  • 2,757
  • 4
  • 26