比方说,我有很多钱,我想给在之间$ 500和$ 5,000个随机的增量。我想的范围内的下端为比较高的范围更为可能。什么是最有效的算法,我可以用Ruby写随机发放现金以这种方式?
Let's say I have lots of cash I want to give out in random increments between $500 and $5,000. I'd like the lower end of the range to be much more probable than the higher range. What's the most efficient algorithm I can write in Ruby to randomly hand out cash in this manner?
我觉得最简单的方法就是只使用case语句:
I think the easiest way is to just use the case statement:
def get_price
case rand(100) + 1
when 1..50 then 500
when 50..75 then 1000
when 75..99 then 2500
when 99..100 then 10000
end
end
p get_price # => 500
调用get_price将返回500以50%的概率,但时间万才会返回2%
Calling get_price will return 500 with 50% probability but 10000 will only be returned 2% of the time.