Reduces the likelihood of selecting a number from a list of consecutive numbers

Say, for example, I am assigned a number 3. Then I need to select a random number from 0 to 3, but where 0 has a greater chance of being selected than 1, 1 has a greater chance of being selected than 2, and 2 has a greater chance of being selected than 3.

I already know that the percentage chance of choosing a certain number from 0 to 3 can be achieved by following these steps:

double r = Math.random();
int n = 0;
if (r < 0.5) {
    n = 0;
    // 50% chance of being 0
} else if (r < 0.8) {
    n = 1;
    // 30% chance of being 1
} else if (r < 0.95) {
    n = 2;
    // 15% chance of being 2
} else {
    n = 3;
    // 5% chance of being 3
}

The problem is that it 3can be anything. How can i do this?

Note. The numbers 0.5, 0.8 and 0.95 were chosen by me arbitrarily. I would expect these numbers to decrease, so that the sum of all of them is 1, and so none of them will be the same if it is possible in any way.

+4
4

, , . , , f(0) = 0 f(1) = 1. f(x) = x^2.

- , 0, :

numbers = ceil(max * f(rand()))

ceil - , max - , , f() - , , rand() - . , 1 max, 0 max.

, :

Graph <code> ceil (f (x)) </code> for <code> max == 10 </code>)

, , .. (max * f (x)) " " 10 "".

, f(x). , - . f(x) - , , , . , f(x) e^x, .

, !


:

public int weightedRandom(int max, Random rand) {
     return Math.ceil(((double) max) * Math.pow(rand.nextDouble(), 2));
}

java- , max == 10:

2.0, 6.0, 8.0, 3.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 7.0, 1.0, 4.0, 1.0, 1.0, 6.0, 8.0, 9.0, 7.0, 5.0
+5

public double nextGaussian() java.util.Random

, Javamex nextGaussian ( )

, 0 n:

:

  • 70% 1
  • 95% 2
  • 99% 3

1


 Random r = new Random();
 int n = 10;
 int res = (int) Math.min(n, Math.abs(r.nextGaussian()) * n / 3);

:

  • n: n
  • 4: , , (99% 3 ), 99% ( n)
  • Math.abs, 0
  • Math.min , , n

10 000 :

bar chart

+3

, , . () : 4

int n = 4 * (1 - Math.sqrt(Math.random()))
0

"" " ", " ". , 50% 4 :

  • 50% 100% 50%, 50%.
  • 50% 50% 25%, 25%.
  • 50% 25% 12,5%, 12,5%.
  • , 100%, (# 4) - (# 3) - 12,5%.

( ) , , , .. 0,5, 0.0 < p < 0,5. , , , . , 0,1 , - 0,0 < p < 0.1, , . , , (, , 0,3 < p < 0,5).

, , <, <=, . , 0.0 <= p <= 0.5, , , , ( ), , 0.0 (.. 100% 0% , , ).

, , 1.0.

0

Source: https://habr.com/ru/post/1681373/


All Articles