title: Generate random number but exclude multiple ranges without looping
body: <p>I'm looking for a mathematical approach for generating a random number between [a, b) with holes at [c, d), [e, f), [g, h) and so on where a &lt; b and the ranges are within the bounds.</p>
  
  <p>I've found numerous examples here on how to do make the algorithm work if there is one missing range but can't seem to find a space/time efficient approach that generalizes to multiple ranges. What I mean here is that both:</p>
  
  <p>a. A list of all possible ranges and choosing from that list: doesn't work well for large ranges</p>
  
  <p>b. Generating a random number and checking if it is one of the ranges, otherwise trying again: unbounded terms of runtime</p>
  
  <p>Some salient test cases might be:</p>
  
  <pre><code>generate_random(start=0, end=100, exclude: [(2,50),(51, 100)])
  generate_random(start=0, end=1e16, exclude: [(1e6,1e7),(1e3, 1e4)])
  </code></pre>
  
  <p>Here are some of the examples I have found:</p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/questions/15591173/generating-a-random-number-between-multiple-ranges">Generating a random number between multiple ranges</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/10666661/can-python-generate-a-random-number-that-excludes-a-set-of-numbers-without-usin">Can Python generate a random number that excludes a set of numbers, without using recursion?</a></p></li>
  </ul>