>>>>> "jct" == Joseph C Tuttle <[EMAIL PROTECTED]> writes:
jct> Is there a simple way in Linux to generate a series of three
jct> hundred to four hundred unique random four digit numbers? I
jct> haven't done enough programming to write my own random number
jct> generator, but I do know Linux can generate them for its own
jct> uses. I have searched man and info pages, and the "Linux
jct> Complete Command Reference," and found tools for programmers to
jct> use to generate random numbers, but that was all I could find.
jct> Is there a simple way for me to do this?
1. Normal random numbers:-
#include <stdlib.h>
int get4digit_pseudo_random(void)
{
return (int)((double)rand() / ((double)RAND_MAX + 1) * 10000)
}
2. Cryptographically strong pseudo-random numbers:-
#include <stdio.h>
#include <limits.h>
int get4digit_pseudo_random(int array[], int N)
{
int i;
FILE *f = fopen("/dev/urandom", "rb");
if (NULL == f)
{
perror("/dev/urandom");
return -1;
}
if (fread(array, sizeof(int), N, f) < N)
{
perror("fread");
return -1;
}
fclose(f);
for (i=0; i<N; ++i)
{
array[i] = (int)((double)array[i] / ((double)INT_MAX + 1) * 10000)
}
}
You can also do this by reading one number from /dev/urandom and using
it as a seed for rand(). In fact, that is probably a better approach
than this chunk of code above.
3. Genuine, real-world random numbers:-
As (2), but use /dev/random rather than /dev/urandom.
This can take a *very* long time. You almost never want to do this.
The use of the number 10000 ensures that the numbers are in the
range 0...9999. That was what you asked for, I think. See the FAQ
for comp.lang.c for why it has to be done this way.
--
PLEASE read the Red Hat FAQ, Tips, Errata and the MAILING LIST ARCHIVES!
http://www.redhat.com/RedHat-FAQ /RedHat-Errata /RedHat-Tips /mailing-lists
To unsubscribe: mail [EMAIL PROTECTED] with
"unsubscribe" as the Subject.