如何以一定比例随机选择 [英] How to choose randomly in a certain ratio

查看:197
本文介绍了如何以一定比例随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要选择随机*不等概率两种选择之间。

例如,当用户presses一个按钮,时间会做出合理的A和75%的时间25%,声音B.我可以手动做容易比像1:4和2:4但我与像3比麻烦:5。

什么是思考这个问题的一般方法是什么?

  

*我的意思是取消predictable时,在一个接一个的照顾。我注意到有任何问题   这个词随机它所获得的门萨   学究的。

解决方案

有关3:5,你可以将它们添加合力得到8,并选择一个随机整数小于8。如果是0,1,或2(三次机会)你选择一个,如果它是3,4,5,6或7(五个机会),你选B. code-明智的你只是检查你的随机数是否小于3。

有关类似3:5:4,你会选择一个随机数小于12(3 + 5 + 4),如果是小于3,你选择A,否则,如果它是低于8(3 + 5)你选择B,否则你选择C。

这可以推广到任意数量的替代品,但它的效率不高,有很多的选择,因为你必须要检查每一个门槛,这是O(n)的随机数。 <一href="http://stackoverflow.com/questions/352670/weighted-random-selection-with-and-without-replacement">This SO质疑似乎提供了一些更有效(但更复杂的)算法加权随机选择具有较大的替代品数量。

I want to choose randomly* between two alternatives with unequal probability.

For instance, when the user presses a button, 25% of the time it would make sound A and 75% of the time, sound B. I can manually do easy ratios like 1:4 and 2:4 but I'm having trouble with ratios like 3:5.

What is the generic way to think about this?

*I mean unpredictable when looked at one-by-one. I notice any question with the word random in it gets a Mensa of pedants.

解决方案

For 3:5 you can add them together to get 8, and pick a random integer less than 8. If it's 0, 1, or 2 (three chances) you choose A, and if it's 3, 4, 5, 6, or 7 (five chances) you choose B. Code-wise you'd just check whether your random number is less than 3.

For something like 3:5:4, you'd pick a random number less than 12 (3+5+4) and if it's less than 3 you choose A, otherwise if it's less than 8 (3+5) you choose B, otherwise you choose C.

This can generalize to any number of alternatives, but it's inefficient with lots of alternatives since you have to check the random number against each threshold, which is O(n). This SO question seems to provide some more efficient (but more complex) algorithms for weighted random selection with larger numbers of alternatives.

这篇关于如何以一定比例随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆