-3

Folks,

I'm trying to generate a random number between (0..10) less, say, 5.

new_index = rand(0..(old_index - 1)) || new_index = rand((old_index + 1)..10)

Can anyone shed any light?

Zonblar
  • 107
  • 5

1 Answers1

1
new_sample_space = (0..10).to_a - [5] #=> [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
new_index = new_sample_space.sample #=> random integer from 0-10, except 5

Of course, doing this with a large range is probably not a good idea because of memory concerns. In such "huge" cases, you could possibly just get another random number after you get 5.

loop do
  new_index = rand(1..10)
  break if new_index != 5
end
cozyconemotel
  • 1,121
  • 2
  • 10
  • 22
  • Your second code has a high probability that it will terminate correctly, but it has a small chance that it will take a long time to terminate or run into an infinite loop. The probability that it will terminate in `n` iterations is `1 - (1/10)^n`. – sawa Jan 17 '16 at 20:31
  • You're right, and that's why I limited its use to "huge" cases.. `(0..100000000).to_a` is expensive but `rand(1..100000000)` is fast and the probability that it will terminate in `n` iterations is `1 - (1/100000000)^n`.. well yeah it's probably not a good idea in production anyways – cozyconemotel Jan 17 '16 at 22:15