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

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

    Method 1

    Using Kent's approach, it is possible to generate an array of arbitrary length keeping all values in a limited range:

    # Generates a random array of length n.
    #
    # @param n     length of the desired array
    # @param lower minimum number in the array
    # @param upper maximum number in the array
    def ary_rand(n, lower, upper)
        values_set = (lower..upper).to_a
        repetition = n/(upper-lower+1) + 1
        (values_set*repetition).sample n
    end
    

    Method 2

    Another, possibly more efficient, method modified from same Kent's another answer:

    def ary_rand2(n, lower, upper)
        v = (lower..upper).to_a
        (0...n).map{ v[rand(v.length)] }
    end
    

    Output

    puts (ary_rand 5, 0, 9).to_s # [0, 8, 2, 5, 6] expected
    puts (ary_rand 5, 0, 9).to_s # [7, 8, 2, 4, 3] different result for same params
    puts (ary_rand 5, 0, 1).to_s # [0, 0, 1, 0, 1] repeated values from limited range
    puts (ary_rand 5, 9, 0).to_s # []              no such range :)
    
    0 讨论(0)
  • 2020-11-28 23:23

    No loops with this method

    Array.new(size) { rand(max) }
    
    require 'benchmark'
    max = 1000000
    size = 5
    Benchmark.realtime do
      Array.new(size) { rand(max) }
    end
    
    => 1.9114e-05 
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题