2013-11-25 35 views
2

我有一系列彩票随机数。红宝石 - 有例外的范围内的随机数

我该如何选择第二个地方的随机数等等,而不必再次拔出第一个地方的风险?

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

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

回答

10

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 
+1

当然,但如果时间是一个问题,他真的不应该分配一个数百万的整数开始。 – hirolau

+0

+1。这个问题正是'sample'的用处。 –

3

如果从一个大阵挑选出一个非常小的数数这可能是聪明,只得到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 

到底什么是快为你依赖于数组的大小,你需要的随机数的数量。

+0

这确实比其他答案更笨拙,但从这样一个大集合中挑选几个数字肯定是正确的算法。 – Max