Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random number between X and Y, excluding certain numbers

Tags:

random

ruby

Is there a way of generating a random number in ruby between, say, 1 - 100 but excluding 20, 30 and 40?

I could do something like

def random_number
  random_number = rand(100) 
  while random_number == 20 || 30 || 40
    random_number = rand(100)
  end
  return random_number
end

...but that doesn't seem very efficient (plus that particular example probably wouldn't even work).

Is there a simpler way? Any help is much appreciated!

like image 596
Jon Avatar asked Aug 07 '11 02:08

Jon


1 Answers

Create an array of 1 to 100. Remove the unwanted elements from this array. Then pick a random number from the array.

([*1..100] - [20, 30, 40]).sample

If the number of elements were huge, say 10 million, then your approach of randomly picking one and retrying if you found an unwanted number would work better. Also if the list of unwanted numbers is long, you could put it in an array or set, and test for membership instead of individually checking each value. So, instead of,

if(x == 20 || x == 30 || x == 40)

you could do,

unwanted_numbers = [20, 30, 40]
if(unwanted_numbers.include?(x))
like image 103
Anurag Avatar answered Oct 01 '22 23:10

Anurag