在 ruby/rails 中生成 n 个唯一的随机整数 [英] Generate n unique random integers in ruby / rails
本文介绍了在 ruby/rails 中生成 n 个唯一的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试生成 1 到最大值之间的 n 个唯一随机数
Im trying to generate n unique random numbers between 1 and max
我尝试了以下代码但不起作用(返回重复的数字)
I tried the following code but doesn't work (returns repeated numbers)
r = [ ]
n.times { v = rand(max) while r.include? v ; r << v}
有什么问题吗?谢谢
添加:
最大为数千
n 是 10
推荐答案
我认为你的 while r.include 逻辑是错误的.试试这个:
I think your while r.include logic is the wrong way around. Try this:
r = [ ]
while r.length < n
v = rand(max)
r << v unless r.include? v
end
请注意,如果 max < 将进入无限循环.n.
Note that this will go into an infinite loop if max < n.
这篇关于在 ruby/rails 中生成 n 个唯一的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文