algorithm - How to choose randomly in a certain ratio -


i want choose randomly* between 2 alternatives unequal probability.

for instance, when user presses button, 25% of time make sound , 75% of time, sound b. can manually easy ratios 1:4 , 2:4 i'm having trouble ratios 3:5.

what generic way think this?

*i mean unpredictable when looked @ one-by-one. notice question word random in gets mensa of pedants.

for 3:5 can add them 8, , pick random integer less 8. if it's 0, 1, or 2 (three chances) choose a, , if it's 3, 4, 5, 6, or 7 (five chances) choose b. code-wise you'd check whether random number less 3.

for 3:5:4, you'd pick random number less 12 (3+5+4) , if it's less 3 choose a, otherwise if it's less 8 (3+5) choose b, otherwise choose c.

this can generalize number of alternatives, it's inefficient lots of alternatives since have check random number against each threshold, o(n). this question seems provide more efficient (but more complex) algorithms weighted random selection larger numbers of alternatives.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -