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!
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With