How do I generate a list of n unique random numbers in Ruby?

后端 未结 15 1836
鱼传尺愫
鱼传尺愫 2020-11-28 22:27

This is what I have so far:

myArray.map!{ rand(max) }

Obviously, however, sometimes the numbers in the list are not unique. How can I mak

15条回答
  •  甜味超标
    2020-11-28 22:58

    [*1..99].sample(4) #=> [64, 99, 29, 49]
    

    According to Array#sample docs,

    The elements are chosen by using random and unique indices

    If you need SecureRandom (which uses computer noise instead of pseudorandom numbers):

    require 'securerandom'
    
    [*1..99].sample(4, random: SecureRandom) #=> [2, 75, 95, 37]
    

提交回复
热议问题