R – 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

What is your solution?

Best Solution

(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.