加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有帐号?注册会员
x
本帖最后由 我为鱼肉 于 2023-1-13 16:35 编辑
随机一个从n到m的数,如何让数越大随机到的概率就越低。
已经解决,这是我按照菜刀提供的思路,定义的方法(比用数组或许能快一点点吧)。
module Kernel def random(range) first = range.first last = range.exclude_end? ? range.last - 1 : range.last max = (last - first + 1) * (first + last) / 2 result = rand(max) + 1 for i in range small = i > first ? ((i - first) * (first + i - 1) / 2) : 0 large = i > first ? ((i - first + 1) * (first + i) / 2) : first break if result > small and result <= large #return i if result > small and result <= large end return last - i + first end end #代码测试 a = [] 1000.times{ r = random(20..40) if a[r].nil? a[r] = 0 end a[r] += 1 } a.delete(nil) p a exit
module Kernel
def random(range)
first = range.first
last = range.exclude_end? ? range.last - 1 : range.last
max = (last - first + 1) * (first + last) / 2
result = rand(max) + 1
for i in range
small = i > first ? ((i - first) * (first + i - 1) / 2) : 0
large = i > first ? ((i - first + 1) * (first + i) / 2) : first
break if result > small and result <= large
#return i if result > small and result <= large
end
return last - i + first
end
end
#代码测试
a = []
1000.times{
r = random(20..40)
if a[r].nil?
a[r] = 0
end
a[r] += 1
}
a.delete(nil)
p a
exit
|