21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Discussion<br />

In all cases, you will start with a function that gives you a random unsigned number<br />

that can be any value, such as spc_rand_uint( ) from Recipe 11.10. You will mold<br />

numbers returned from this function into numbers in a specific range.<br />

If you need random numbers in a particular range, the general approach is to get a<br />

number between zero and one less than the number of values in the range, then add<br />

the result to the smallest possible value in the range.<br />

Ideally, when picking a random number in a range, you would like every possible<br />

value to be equally likely. However, if you map from an arbitrary unsigned integer<br />

into a range, where the range does not divide evenly into the number of possible integers,<br />

you are going to run into problems.<br />

Suppose you want to create a random number in a range using an unsigned 8-bit<br />

type. When you get a random unsigned 8-bit value, it can take on 256 possible values,<br />

from 0 to 255. If you are asking for a number between 0 and 9 inclusive, you<br />

could simply take a random value and reduce it modulo 10.<br />

The problem is that the numbers 0 through 5 are more likely values than are 6<br />

through 9. 26 possible values will reduce to each number between 0 and 5, but only<br />

25 values will yield 6 through 9.<br />

In this example, the best way to solve this problem is to discard any random numbers<br />

that fall in the range 250-255. In such a case, simply get another random value and try<br />

again. We took this approach in implementing the function spc_rand_range( ). The<br />

result will be a number greater than or equal to a minimum value and less than or<br />

equal to maximum value.<br />

#include <br />

#include <br />

Some programmers may expect this function to exclude the upper<br />

limit as a possible value; however, we implement this function in such<br />

a way that it is not excluded.<br />

int spc_rand_range(int min, int max) {<br />

unsigned int rado;<br />

int range = max - min + 1;<br />

if (max < min) abort( ); /* Do your own error handling if appropriate.*/<br />

do {<br />

rado = spc_rand_uint( );<br />

} while (rado > UINT_MAX - (UINT_MAX % range));<br />

return min + (rado % range);<br />

}<br />

Getting a Random Integer in a Range | 607<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!