【问题标题】:Ruby - Random number in range with exceptionsRuby - 范围内的随机数,但有例外
【发布时间】:2013-11-25 12:16:23
【问题描述】:

我有一系列随机数的彩票。

我怎样才能选择第二名的随机数等等,而不会有再次拔出第一名的风险?

$first = rand(0..99999)
$second = rand(0..99999)
$third = rand(0..99999)

我需要在下面的图中找到某种异常。

【问题讨论】:

    标签: ruby exception random


    【解决方案1】:

    shuffle 将置换整个数组,这对于大型数组可能会很慢。 sample 是一个更快的操作

    (1..99999).to_a.sample(3)
    

    出于基准测试目的:

    > require 'benchmark'
    > arr = (0..99999).to_a; 0
    > Benchmark.realtime { 10_000.times { arr.sample(3) } }
    => 0.002874
    > Benchmark.realtime { 10_000.times { arr.shuffle[0,3] } }
    => 18.107669
    

    【讨论】:

    • 当然,但是如果时间是个问题,他真的不应该分配一百万个整数的数组。
    【解决方案2】:

    如果您要从一个大数组中挑选出非常少的数字,那么只获取 3 个随机数并检查它们是否不同可能是明智之举:

    def create_array_and_pick_three
      arr = (0..99999).to_a
      arr.sample(3)
    end
    
    def get_three_random_until_uniq
      array, num = [], 3
      array = (1..num).map{rand(0..99999)} until array.uniq.size == num
    end
    
    
    p Benchmark.realtime { 1000.times { create_array_and_pick_three }} #=> 4.343435
    p Benchmark.realtime { 1000.times { get_three_random_until_uniq }} #=> 0.002
    

    究竟什么对你来说更快取决于数组的大小和你需要的随机数的数量。

    【讨论】:

    • 这肯定比其他答案更笨拙,但要从这么大的集合中挑选几个数字,它绝对是正确的算法。
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2011-09-06
    相关资源
    最近更新 更多