An elegant way to get a random percentage value?

I have N values ​​(integer). I would like to know what is the most elegant way to randomly select one of these values ​​in terms of percentage. For example, for an example of 3 values:

  • Value 1 has a 30% chance of getting the selected
  • Value 2 has a 12% chance to get the selected
  • Value 3 has a 45% chance of getting the selected

I need this for a program that I am developing using Java, but a pseudo-code algorithm or code in any other language will be fine.

+4
source share
2 answers

One way to do this without calculating the values ​​used is

double d = Math.random() * 100; if ((d -= 30) < 0) return 1; if ((d -= 12) < 0) return 2; if ((d -= 45) < 0) return 3; return 4; 
+11
source

Suggested Algorithm:

  • generates a random number ( n ) between 0 and 1 (if your random generator is well distributed)
  • if n < 0.30 return value 1
  • if n < 0.42 return value 2
  • else if n < 0.87 return value 3
  • else say Hello (your numbers are not up to 100%)
+8
source

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


All Articles