如何生成介于0和n之间的随机数?


当前回答

也许这对你有帮助。我在应用程序中使用此功能

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

这对我来说很好

其他回答

别忘了先用srand()为RNG种子。

这个呢?

n = 3
(0..n).to_a.sample

也许这对你有帮助。我在应用程序中使用此功能

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

这对我来说很好

尝试array#shuffle方法进行随机化

array = (1..10).to_a
array.shuffle.first

虽然您可以使用rand(42-10)+10来获得10到42之间的随机数(其中10是包含的,42是不包含的),但自Ruby 1.9.3以来,有一种更好的方法,您可以调用:

rand(10...42) # => 13

通过需要我的backports gem,可用于所有版本的Ruby。

Ruby1.9.2还引入了Random类,因此您可以创建自己的随机数生成器对象,并具有一个很好的API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

Random类本身充当随机生成器,因此可以直接调用:

Random.rand(10...42) # => same as rand(10...42)

关于Random.new的注释

在大多数情况下,最简单的方法是使用rand或Random.rand。每次你想要一个随机数时,创建一个新的随机生成器是一个非常糟糕的主意。如果您这样做,您将获得初始种子算法的随机财产,与随机生成器本身的财产相比,这些属性非常糟糕。

如果您使用Random.new,那么应该尽可能少地调用它,例如,一次调用MyApp::Random=Random.nnew,并在其他地方使用它。

Random.new有帮助的情况如下:

您正在编写一个gem,不想干扰主程序可能依赖的rand/Random.rand序列您需要单独的可重复随机数序列(例如每个线程一个)您希望能够保存和恢复可复制的随机数序列(就像随机对象可以编组一样简单)