On Wed, Jul 01, 1998 at 12:40:21PM -0400, Joseph C. Tuttle wrote:
> Is there a simple way in Linux to generate a series of three hundred to
> four hundred unique random four digit numbers?  I haven't done enough
> programming to write my own random number generator, but I do know Linux
> can generate them for its own uses.  I have searched man and info pages,
> and the "Linux Complete Command Reference," and found tools for
> programmers to use to generate random numbers, but that was all I could
> find.  Is there a simple way for me to do this?
> 
> Any help would be appreciated.

Entirely off the top of my head (and therefore totally untested) something
akin to the following ought to get you near where you want to go.

If you really need unique numbers, the only way to ensure that is to store
them all in an array, and for each new generated number, scanthe array to
check for duplication and discard if duplicated. If uniqueness is not
required, it's easy.

#include <stdlib.h>
#define NUMRAND 400
main (void)
        {
        int randstor[NUMRAND];
        int numrand, j;
        int tmprand;
        char tmpbuf[10];

        srand (time(0));        /* seed the generator */
        for (numrand = 0 ; numrand < NUMRAND ; numrand++)
                {
                /* in the range of 1-9999 */
                tmprand = 1 + (int) (9999.0 * rand() / (RAND_MAX + 1.0));

                /* check for uniqueness */
                for (j = 0 ; j < numrand; j++)
                        {
                        if (randstor[j] == tmprand)
                                break;
                        }
                if (j >= numrand)       /* if unique */
                        randstor[numrand] = tmprand;
                else                                    /* if NOT unqiue */
                        numrand--;
                }
        for ( j = 0 ; j < NUMRAND ; j++ )
                printf ("item %d: %04d\n", j, randstor[j]);
        }
-- 
---- Fred Smith -- [EMAIL PROTECTED] ----------------------------
                    The Lord detests the way of the wicked 
                  but he loves those who pursue righteousness.
----------------------------- Proverbs 15:9 (niv) -----------------------------


-- 
  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.

Reply via email to