🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: rec.games.programmer
Article #1173

Re: Card Shuffling

#1173
From: Holger Joist
Date: Thu, 12 Nov 1992 15:47
51 lines
1730 bytes
HeroSoftware@cup.portal.com (Bits of Magic) writes:

>A quick and dirty way is:

>	Card	deck[DECKSIZE];

>	for (i=0;i<DECKSIZE;i++)
>		deck[i] = i;

>	for (i=0;i<SWAPS;i++) {
>		firstcard = random(DECKSIZE);
>		secondcard = random(DECKSIZE);
>		temp = deck[firstcard];
>		deck[firstcard] = deck[secondcard];
>		deck[secondcard] = temp;
>	}

>where your Card values run from 0 to DECKSIZE (say 52 or 54), random(N)
>returns a random integer in the range 0 to N-1 (inclusive), and SWAPS
>is (as I recall from a project many years ago) at least about 100.

The problem with this method is that the exchanges can wipe out each other.

I think a better way is:

/* initialize */
for (i = 0; i < DECKSIZE; i++)
	deck[i] = i;

/* choose one element randomly,       */
/* exchange it with the last element, */
/* repeat with the rest of the deck   */

for (i = DECKSIZE - 1; i >= 0; i--)
{
	rnd = random(i + 1);
	x = deck[i];
	deck[i] = deck[rnd];
	deck[rnd] = x;
}


Using that  method  you  get  a  perfect  permutation.  And  this
alorithm  works  for  every  DECKSIZE  (Asuming  random() is good
enough) in only DECKSIZE loops.


Holger
-- 
Snail: Holger Joist, Neue Strasse 29, 8520 Erlangen, Germany
Email: hrjoist@immd4.informatik.uni-erlangen.de
Technical Details
Message-ID: <BxM16o.2n@immd4.informatik.uni-erlangen.de>
Path: arc1-ca.pugleaf.net!sparky!uunet!think.com!yale.edu!ira.uka.de!fauern!fauna!hrjoist
References: <1992Nov6.163008.19400@csi.uottawa.ca> <69216@cup.portal.com>

Show Full Headers
Complete Article Headers
Newsgroups: rec.games.programmer
Path: arc1-ca.pugleaf.net!sparky!uunet!think.com!yale.edu!ira.uka.de!fauern!fauna!hrjoist
From: hrjoist@immd4.informatik.uni-erlangen.de (Holger Joist)
Subject: Re: Card Shuffling
References: <1992Nov6.163008.19400@csi.uottawa.ca> <69216@cup.portal.com>
Message-ID: <BxM16o.2n@immd4.informatik.uni-erlangen.de>
Organization: CSD., University of Erlangen, Germany
Date: Thu, 12 Nov 1992 15:47:12 GMT
Lines: 51