Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - Generate a random number outside of a range without a loop

Tags:

c

random

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.

like image 814
edt11x Avatar asked Dec 02 '25 10:12

edt11x


1 Answers

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

like image 57
klutt Avatar answered Dec 04 '25 23:12

klutt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!