如何在 Ruby 中生成 n 个唯一随机数的列表? [英] How do I generate a list of n unique random numbers in Ruby?

查看:25
本文介绍了如何在 Ruby 中生成 n 个唯一随机数的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前所拥有的:

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屋!

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