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

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

    If you have a finite list of possible random numbers (i.e. 1 to 100), then Kent's solution is good.

    Otherwise there is no other good way to do it without looping. The problem is you MUST do a loop if you get a duplicate. My solution should be efficient and the looping should not be too much more than the size of your array (i.e. if you want 20 unique random numbers, it might take 25 iterations on average.) Though the number of iterations gets worse the more numbers you need and the smaller max is. Here is my above code modified to show how many iterations are needed for the given input:

    require 'set'
    
    def rand_n(n, max)
        randoms = Set.new
        i = 0
        loop do
            randoms << rand(max)
            break if randoms.size > n
            i += 1
        end
        puts "Took #{i} iterations for #{n} random numbers to a max of #{max}"
        return randoms.to_a
    end
    

    I could write this code to LOOK more like Array.map if you want :)

提交回复
热议问题