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

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

    As far as it is nice to know in advance the maxium value, you can do this way:

    class NoLoopRand
      def initialize(max)
        @deck = (0..max).to_a
      end
    
      def getrnd
        return @deck.delete_at(rand(@deck.length - 1))
      end
    end
    

    and you can obtain random data in this way:

    aRndNum = NoLoopRand.new(10)
    puts aRndNum.getrnd
    

    you'll obtain nil when all the values will be exausted from the deck.

提交回复
热议问题