Re: Randomly selecting an element from an STL collection
On Jun 30, 2:42 pm, Markus Schoder <a3vr6dsg-use...@yahoo.de> wrote:
On Fri, 29 Jun 2007 09:13:21 +0000, James Kanze wrote:
The problem doesn't occur if RAND_MAX + 1 is a multiple of your value,
so the usual solution is just to throw out any values above the last
multiple. For a random value in the range 0...N-1, I use something
like:
unsigned const limit = RAND_MAX+1 - (RAND_MAX+1) % N ;
That is almost guaranteed to fail on many implementations namely those
that have RAND_MAX equal to INT_MAX (e.g. gcc on x86(-64)).
Good point. I actually copied it from my own implementation of
RandomInt, which is based on my own random number generator,
with known properties, modifying it to use RAND_MAX+1, rather
than Random::max(). (In my case, Random::max() defines the
upper bound of a half open interval, i.e. is exclusive. And my
own generator uses linear congruence, so it isn't be a power of
2.)
At least make it RAND_MAX+1u. That should work on most implementations.
I think I'd cast RAND_MAX to unsigned; that u can easily be
overlooked:-).
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34