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

后端 未结 15 1794
鱼传尺愫
鱼传尺愫 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 23:24

    You could use a hash to track the random numbers you've used so far:

    seen = {}
    max = 100
    (1..10).map { |n|
      x = rand(max)
      while (seen[x]) 
        x = rand(max)
      end
      x
    }
    

提交回复
热议问题