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

后端 未结 15 1815
鱼传尺愫
鱼传尺愫 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:06

    Ruby 1.9 offers the Array#sample method which returns an element, or elements randomly selected from an Array. The results of #sample won't include the same Array element twice.

    (1..999).to_a.sample 5 # => [389, 30, 326, 946, 746]
    

    When compared to the to_a.sort_by approach, the sample method appears to be significantly faster. In a simple scenario I compared sort_by to sample, and got the following results.

    require 'benchmark'
    range = 0...1000000
    how_many = 5
    
    Benchmark.realtime do
      range.to_a.sample(how_many)
    end
    => 0.081083
    
    Benchmark.realtime do
      (range).sort_by{rand}[0...how_many]
    end
    => 2.907445
    

提交回复
热议问题