In C, I can use this simple expression to generate a random number in a range:
rand() % (max_number + 1 - minimum_number) + minimum_number
Is there a similar, non loop based expression that can generate a random number outside a range? For example if my range is from 3 to 5, I would want a random number that would either be in the range 0 to 2, or 6 to RAND_MAX.
This would work:
int r = rand() % (maxval+1 - rangesize);
if(r>=rangemin)
r+=rangesize;
From your example, rangesize would be 3 since there are three numbers in the range you want to avoid, and rangemin would be 3 because it is the smallest number in that range.
This would produce random numbers in the range [0, maxval] except numbers in the range [rangemin, rangemin+rangesize-1]
However, do note that using rand() % x often gives a bad distribution, so if that matters you need to think about that. Thanks to rici for pointing this out. See his answer for more information about this.
But given that you have a function r(lo, hi) that generates uniformly distributed numbers from lo to hi, the transformation if(r>=rangemin) r+=rangesize will work just fine and not mess up the distribution.
Relevant links:
Generating a uniform distribution of INTEGERS in C
http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx
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