random number generator

T

tao_benz

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
 
M

Mike Wahler

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
 
M

Mike Wahler

/* 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
 
M

Michael Wohlwend

Mike said:
/* 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
 
P

Pete Becker

Mike said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top