Random Number Between Two Integers
Tuesday, December 8th, 2009Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
This is a topic that is quite easy and doesn’t need much explanation but still many people manage to mess it up. Not going into a hyperbole, I’ll get straight to the point. When asked, people can quickly tell you how to get a random number between 0 and b (b being any number below the maximum random number possible, which is defined as RAND_MAX by most C compilers). Using the function “rand” provided by most C libraries, this is as simple as:
result = rand() % b;
Basically, given any random number, if you take its modulus with a, you will obviously get a number between 0 and a -1. This is all fine and dandy, so now someone asks you to generate a random number between a and b (a < b). This one is also really simple but few people fumble out still. Just think of it this way.
- If you add 1 to the above equation’s right hand side, your random number will be between 1 and a. So, basically your “lower limit” is raised by one. In the above case, your lower limit is a, so just raise it by a by adding it to right hand side, to arrive at this partial solution.
result = rand() % b + a;
- To complete the equation, now think of the gap between the minimum and maximum result obtained from original equation. Minimum is 0 and maximum is (b-1). But your desired gap is (b-a). Since taking modulus with respect to b, gives you a gap of b-1, to get the desired gap, you need to take mod with respect to ((b-a)+1). So, minimum value this will give you is 0 and maximum would be (b-a) +1 -1 = b-a. So, your final equation becomes
result = rand() % (b - a + 1) + a;
This will give you a minimum value of 0 + a = a
and a maximum of b – a + a = b.
Note that the above solution includes the limits for the result. If you don’t want to include the limits (i.e. minimum result = a + 1 and maximum result = b – 1) and , then just add (a + 1) instead of a in step 1 and use (b – a -1) for your modulus operation instead of (b – a + 1) in step 2 to make the equation:
result = rand() % (b - a - 1) + a + 1;
Note that in the above equation we used b – a -1, though on the surface it looks like we could have gone with just (b-a). After all we just wanted to decrease the upper limit by 1. But the reason we had to decrement by an extra place is because of the 1 we added to raise the lower limit (a +1).
© Safer Code | Random Number Between Two Integers
|
Liked this post? Get FREE Updates Subscribe to RSS feed |