Jon
Jon

Reputation: 3985

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

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!

Upvotes: 6

Views: 5132

Answers (1)

Anurag
Anurag

Reputation: 141879

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))

Upvotes: 24

Related Questions