# random number generator

Discussion in 'C++' started by tao_benz@hotmail.com, Aug 11, 2005.

1. ### Guest

Hi:
My system generates a bunch of integers, about 1000. There is no any
relationship between those integers; the smallest one might only
contain 1 digit and the biggest one might contain 6 digits. How can I
pick the random 100 numbers from the 1000 numbers. Thanks in advance.

tao

, Aug 11, 2005

2. ### Mike WahlerGuest

<> wrote in message
news:...
> Hi:
> My system generates a bunch of integers, about 1000. There is no any
> relationship between those integers; the smallest one might only
> contain 1 digit and the biggest one might contain 6 digits. How can I
> pick the random 100 numbers from the 1000 numbers. Thanks in advance.
>
> tao

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NUM_COUNT 1000
#define SEL_COUNT 100

/* Returns random number between 'low' and 'high' inclusive */
/* */
/* (Formula derived from that given in the C FAQ */
/* http://www.eskimo.com/~scs/C-faq/top.html */
/* See section 13 */
int rand_range(int low, int high)
{
return (int)((double)
rand() / ((double)RAND_MAX + 1) * (high - low + 1));
}

int main()
{
int numbers[NUM_COUNT] = {0}; /* the NUM_COUNT numbers */
size_t i = 0; /* for array iteration */

srand((unsigned int)time(0)); /* seed RNG */

/* generate NUM_COUNT random numbers and store in an array */
for(i = 0; i < sizeof numbers / sizeof *numbers; ++i)
numbers = rand();

/* display SEL_COUNT random elements of the array */
for(i = 0; i < SEL_COUNT; ++i)
printf("%4d :%8d\n", i + 1, numbers[rand_range(0, 999)]);

return 0;
}

-Mike

Mike Wahler, Aug 11, 2005

3. ### Mike WahlerGuest

Re: (corr) random number generator

"Mike Wahler" <> wrote in message
news:xgxKe.4155\$...

> /* display SEL_COUNT random elements of the array */
> for(i = 0; i < SEL_COUNT; ++i)
> printf("%4d :%8d\n", i + 1, numbers[rand_range(0, 999)]);

Make that:

> printf("%4d :%8d\n", i + 1, numbers[rand_range(0, SEL_COUNT - 1)]);

-Mike

Mike Wahler, Aug 11, 2005
4. ### Michael WohlwendGuest

Mike Wahler wrote:

> /* Returns random number between 'low' and 'high' inclusive */
> /* */
> /* (Formula derived from that given in the C FAQ */
> /* http://www.eskimo.com/~scs/C-faq/top.html */
> /* See section 13 */
> int rand_range(int low, int high)
> {
> return (int)((double)
> rand() / ((double)RAND_MAX + 1) * (high - low + 1));
> }

isn't there a '+ low' missing somewhere, to really return a number between
low and high?

Michael

Michael Wohlwend, Aug 11, 2005
5. ### Pete BeckerGuest

Mike Wahler wrote:
> return (int)((double)
> rand() / ((double)RAND_MAX + 1) * (high - low + 1));

This just hides the problem. Count your way through the simple case
where RAND_MAX is six and high-low is five.

What you need to do is discard some high values so that max+1 (where max
is the largest value that you keep) is divisible by high-low+1.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)

Pete Becker, Aug 11, 2005