Path: csiph.com!weretis.net!feeder6.news.weretis.net!panix!.POSTED.panix3.panix.com!not-for-mail From: John Forkosh Newsgroups: comp.lang.c Subject: Re: Compute Unique Numbers in a Set Date: Sun, 15 Jan 2023 02:49:50 -0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Message-ID: References: Injection-Date: Sun, 15 Jan 2023 02:49:50 -0000 (UTC) Injection-Info: reader2.panix.com; posting-host="panix3.panix.com:166.84.1.3"; logging-data="29585"; mail-complaints-to="abuse@panix.com" User-Agent: tin/2.6.0-20210823 ("Coleburn") (NetBSD/9.3 (amd64)) Xref: csiph.com comp.lang.c:168812 Albert wrote: > Is this the best way to generate unique random numbers in a set of 6 > numbers? I think what you're looking for (not sure whether or not it's already been mentioned in this long thread) is a "partial permutation", swapping used numbers with unused ones, but we don't need to save the used ones. Here's my general solution, and cc -DTESTDRIVE for the main() test driver... /* --- * uniqrand.c * Generate nuniq random numbers in the range lorand...hirand * --- * (optional) command-line arguments: * ./uniqrand nuniq lorand hirand seedval * 100 1 999 864297531 <-- default test values * ------------------------------------------------------------------------ */ /* --- standard headers --- */ #include #include #include /* for MIN(i,j) macro */ /* --- standard headers --- */ #include #include #include /* for MIN(i,j) macro */ /* --- entry point --- */ int *uniqrand ( int nuniq, int lorand, int hirand ) { /* --- allocations and declarations --- */ int iuniq = 0; /* index 0...nuniq-1 */ int range = 1+abs(hirand-lorand); /* random number range */ int *randvals = NULL, /* nuniq ints returned to caller */ *rangevals = NULL; /* all numbers lorand...hirand */ /* --- initialization --- */ if ( nuniq<1 || nuniq>range ) goto end_of_job; /* input error */ randvals = (int *)malloc((nuniq+99)*sizeof(int)); /* caller free()'s */ rangevals = (int *)malloc((range+99)*sizeof(int)); /* we free() work area */ if ( randvals==NULL || rangevals==NULL ) goto end_of_job; /* malloc error */ rangevals[0] = MIN(lorand,hirand); /* in case hirand1? atoi(argv[1]) : 100 ), lorand = ( argc>2? atoi(argv[2]) : 1 ), hirand = ( argc>3? atoi(argv[3]) : 999 ), seedval = ( argc>4? atoi(argv[4]) : 164897532 ); /* --- allocations and declarations --- */ int *uniqrand(), *randvals=NULL; /* randvals from uniqrand() */ int iuniq = 0; /* randvals[] index */ /* --- initialization --- */ if ( seedval > 0 ) srand(seedval); /* initialize rand() */ /* --- call uniqrand() and display results --- */ if ( (randvals=uniqrand(nuniq,lorand,hirand)) == NULL ) goto end_of_job; for ( iuniq=0; iuniq