如何在Ruby中生成n个唯一随机数的列表? [英] How do I generate a list of n unique random numbers in Ruby?
本文介绍了如何在Ruby中生成n个唯一随机数的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止所拥有的:
This is what I have so far:
myArray.map!{ rand(max) }
但是,显然,有时列表中的数字不是唯一的.如何确保我的列表仅包含唯一数字,而不必创建更大的列表,然后从中选择n个唯一数字?
Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?
修改:
我真的很想看看这个没有循环的完成-可能的话.
I'd really like to see this done w/o loop - if at all possible.
推荐答案
此方法使用Set:
require 'set'
def rand_n(n, max)
randoms = Set.new
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
这篇关于如何在Ruby中生成n个唯一随机数的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文