Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Random number in range with exceptions

I have a series of random numbers for a lottery.

How can i chose the random number for the second place and so on, without having the risk of pulling out the first place again?

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

I need to get some sort of exception in the following drawings.

like image 227
Christian Avatar asked Mar 19 '26 16:03

Christian


1 Answers

shuffle will permute the entire array, which is potentially slow for large arrays. sample is a much faster operation

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

For benchmarking purposes:

> 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
like image 132
Gareth Avatar answered Mar 22 '26 10:03

Gareth