🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: alt.comp.lang.learn.c-c++
Article #178

Re: Array of different random ints

#178
From: Mark Blattner
Date: Sun, 25 Oct 1998 00:00
33 lines
2269 bytes
On Sun, 25 Oct 1998 12:00:43 -0500, "Christian Duffett" <IWM@BAKA.COM>
wrote:

>I need to create an array which has all different integers.  I need this to
>not be of N squared efficiency.  Any ideas ?

This doesn't really have anything to do with C or C++, but...

The straightforward approach is to simply use a linear congruential
generator function; see Knuth's "The Art of Computer Programming,
volume 2:  Seminumerical Algorithms".

These functions generate a sequence of pseudorandom numbers, and for
suitably chosen coefficients, the sequence is guaranteed not to repeat
any number until all generated numbers have been returned once.  That
is, for instance, if the range of output integers is 0 to 65535, then
each such integer will be output exactly once before any such integer
comes out twice.

The functions are of the form:  I(j+1) = ((aI(j) + c) mod m), where
I(j) is the j'th random result (or the seed, the first time), and
I(j+1) is the following random result.  a is the multiplier, c is the
increment, and m is the modulus.  m is chosen for convenience's sake,
and is typically 2^32 or a similar machine-word-size-related value.

a and c must be carefully chosen to achieve the desired
non-repetitiveness property.

As with any computerized "random" number generator, you must make a
tradeoff between ease of computation and "greater randomness".  Linear
congruential generators are very common in runtime libraries, but are
not really all that random.  Usually, though, you don't really care
about this defect for normal purposes.
Technical Details
Message-ID: <3633b224.19307486@news.efortress.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail
References: <dLJY1.2045$sP.7573@newsfeed.slurp.net>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 114592,6bedee75033a460e
X-Google-Attributes: gid114592,public
X-Google-Thread: 10d4ba,6bedee75033a460e
X-Google-Attributes: gid10d4ba,public
From: mark@digitalpla.net (Mark Blattner)
Subject: Re: Array of different random ints
Date: 1998/10/25
Message-ID: <3633b224.19307486@news.efortress.com>
X-Deja-AN: 405009559
References: <dLJY1.2045$sP.7573@newsfeed.slurp.net>
X-Trace: news6.ispnews.com 909358719 204.164.171.154 (Sun, 25 Oct 1998 18:38:39 EDT)
Organization: Foxware Inc.
Reply-To: mark@digitalpla.net
NNTP-Posting-Date: Sun, 25 Oct 1998 18:38:39 EDT
Newsgroups: alt.comp.lang.learn.c-c++,att.lang.c++