Elegant way to generate a random value regarding percentage?

狂风中的少年 提交于 2019-12-09 13:44:12

问题


I have N values (integer). I'd like to know what is the most elegant way to randomly pick one of those values regarding a percentage. For example, for a 3 values example:

  • Value 1 has 30% chance to get picked
  • Value 2 has 12% chance to get picked
  • Value 3 has 45% chance to get picked

I need this for a program i'm developing with Java but a pseudo code algorithm or a code in any other language would be ok.


回答1:


One way of doing this without calculating values to use 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;



回答2:


Proposed algorithm:

  • generate a random number (n) between 0 and 1 (assuming 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 don't add up to 100%)


来源:https://stackoverflow.com/questions/12672765/elegant-way-to-generate-a-random-value-regarding-percentage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!