Path: csiph.com!news.mixmin.net!eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Compute Unique Numbers in a Set Date: Sun, 01 Jan 2023 23:53:52 -0800 Organization: A noiseless patient Spider Lines: 63 Message-ID: <86a631qsmn.fsf@linuxsc.com> References: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader01.eternal-september.org; posting-host="60a7a09099a9247382aee0cc66dfd4bb"; logging-data="1798533"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19hTLSPf1xHVcKcb9H7F28yCFIuicStsIE=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:CwBFX/+w081Fwjp3uYon9Kp+1rI= sha1:bansTK3OfC/I/ONNpIGHnFkrIh8= Xref: csiph.com comp.lang.c:168705 jak writes: > Il 02/01/2023 00:19, Kenny McCormack ha scritto: > >> In article , Albert wrote: >> >>> Is this the best way to generate unique random numbers in a set of >>> 6 numbers? >>> >>> >>> <******************************************************> >> >> Here's my contribution to this thread. >> >> Note that this is both gcc- and Linux- specific, as well as being >> hard-coded to OP's problem specification. Note also that I took >> the liberty of assuming that OP actually, really, did want random >> numbers between 0 and 59; this would be suitable if, say, OP was >> looking for a random number of minutes or seconds (and we could be >> talking either about time intervals or about locations/distances >> expressed in terms of latitude and/or longitude). >> >> --- Cut Here --- >> #include >> #include >> >> int main(void) >> { >> uint64_t num = 0, j = 1; >> FILE *fp = fopen("/dev/urandom","r"); >> >> while (__builtin_popcount(num) < 6) >> num |= 1 << (fgetc(fp) % 60); >> >> for (int i=0; i<60; i++, j *= 2) >> if (num & j) >> printf("i = %d, j = %ld\n",i,j); >> return 0; >> } >> --- Cut Here --- >> >> The values printed out of the variable "i" are your random numbers. > > HI, > I state that I have not worried about the randomization algorithm > chosen by the OP and, so I focused on data storage. Your storage > method is similar to mine because both algorithms use a lookup table > with the difference that mine uses an array of characters while your > use the bits of an uint64_t. However I found a few Issues in your > source code: > > The first concerns the use of the "__builtin_popcount" function, this > function does not work with uint64_t but with unsigned int. [...] > > The second issue concerns that your program will print the values > archived in numerical order and not in extraction order but perhaps > this does not affect the OP even if reading his code this seemed > important. A third problem is that the way the [ 0 .. 59 ] values are chosen is horribly biased: some numbers are 25% more likely than others.