【问题标题】:How to generate a random number between a and b in Ruby?如何在 Ruby 中生成 a 和 b 之间的随机数?
【发布时间】:2011-05-22 15:49:52
【问题描述】:

要生成一个介于 3 到 10 之间的随机数,例如,我使用:rand(8) + 3

有没有更好的方法来做到这一点(比如rand(3, 10))?

【问题讨论】:

  • def my_rand(x, y); rand(y - x) + x; end
  • @Theo,y - x + 1,顺便说一句。
  • 在 10 和 10**24 上尝试你的正确答案,因为限制:0 将等待很长时间 :)
  • 这工作:rand(3..10)

标签: ruby random range


【解决方案1】:

更新:Ruby 1.9.3 Kernel#rand 也接受范围

rand(a..b)

http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html

转成数组可能成本太高,没必要。


(a..b).to_a.sample

或者

[*a..b].sample

Array#sample

Ruby 1.8.7+ 中的标准。
注意:在 1.8.7 中被命名为#choice,并在以后的版本中重命名。

但是无论如何,生成数组需要资源,而你已经写的解决方案是最好的,你可以做到。

【讨论】:

  • 谢谢!我想我会继续使用旧的和好的方法:)
  • 这是一个非常糟糕的主意,尤其是如果您的 a 和 b 大小未知。试试 (100000000000000000..100000000000000).to_a.sample 看看我的意思:)
  • @pixelearth,如果你有更好的想法,符合问题,欢迎发帖。
  • rand(a..b) 不起作用,它会分裂:TypeError: can't convert Range into Integer。 Ruby 2.0 甚至不支持它
  • @fguillen 它在 1.9.3 中对我有用,我不知道为什么它对你不起作用。
【解决方案2】:
Random.new.rand(a..b) 

a 是您的最低值,b 是您的最高值。

【讨论】:

  • 需要注意的重要区别是,如果您只是调用rand(),那么您调用的是Kernel#rand,它只支持max 参数。如果你想传递一个范围,你必须使用Random#rand,这意味着你必须以这种方式实现。 +1
  • 应该补充一下,以上适用于1.9.2
  • 是否包含a和b?
【解决方案3】:
rand(3..10)

Kernel#rand

当 max 是 Range 时,rand 返回一个随机数,其中 range.member?(number) == true。

【讨论】:

    【解决方案4】:

    请注意范围运算符之间的区别:

    3..10  # includes 10
    3...10 # doesn't include 10
    

    【讨论】:

      【解决方案5】:
      def random_int(min, max)
          rand(max - min) + min
      end
      

      【讨论】:

        【解决方案6】:

        参见this 回答:Ruby 1.9.2 中有,但早期版本中没有。我个人认为 rand(8) + 3 很好,但如果您有兴趣查看链接中描述的 Random 类。

        【讨论】:

          【解决方案7】:

          对于 10 和 10**24

          rand(10**24-10)+10
          

          【讨论】:

          • 或者只是rand(10..10**24)
          【解决方案8】:

          这里是#sample 和#rand 的快速基准测试:

          irb(main):014:0* Benchmark.bm do |x|
          irb(main):015:1*   x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
          irb(main):016:1>   x.report('rand') { 1_000_000.times { rand(1..100) } }
          irb(main):017:1> end
                 user     system      total        real
          sample  3.870000   0.020000   3.890000 (  3.888147)
          rand  0.150000   0.000000   0.150000 (  0.153557)
          

          所以,rand(a..b) 是正确的做法

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-10-13
            相关资源
            最近更新 更多