2

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.

2 Answers 2

10

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Sure, but if the time is an issue he really should not allocate an array of a million integers to begin with.
3

If you are picking out a very small number of numbers from a large array it might be smart to just get 3 random numbers and the check that they are different:

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 

Exactly what is faster for you depends on the size of the array and the number of random numbers you need.

1 Comment

This is certainly clumsier to code than the other answers, but for picking a few numbers out of such a large set it is definitely the correct algorithm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.