Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random number excluding range

How do you generate a random number within a range while excluding certain range(s). Eg. range 1-10 but not in 2-4 or 7. Solutions I've used so far:

  • Generate a random an test if it is within the dis-allowed range. Based on result either output the number or try again.
  • Map allowed ranges to a uniform range. Get a random between 1 and 6 and then map back (ie. 6 becomes 10).
  • Create allowed ranges (1-1,5-6,8-10). Randomly choose a range (optionally use weights) and a number in chosen range.

What is your solution?

like image 765
Goran Avatar asked Oct 12 '08 20:10

Goran


2 Answers

(b) Use the single range and map to allowed values.

(a) Is slower and running time is non-deterministic because you have to wait until you get a number in the right range. If you were to skip a large range, you'd be hosed.

(c) Is more complex than (b); don't add complexity if it isn't required.

like image 175
Jason Cohen Avatar answered Sep 19 '22 01:09

Jason Cohen


It would depend on how many/big the exclusion ranges are. Testing for dis-allowed range (your option 1) would work fine for small sets; no need to complicate the solution to an easy problem. Solution 3 would work better for more numerous exclusion sets. Solution 2 is the most work, but probably the most correct theoretical solution.

like image 41
Nick Avatar answered Sep 18 '22 01:09

Nick