Yamin <ab*****@sdfdasfsd.com> wrote in message

news:1c*******************@news01.bloor.is.net.cab le.rogers.com...

"Graeme" <mt*******@aol.com> wrote in message

news:1c**************************@posting.google.c om... I am writing a simple windows matching game with cards and pictures

(ie "concentration"). In order to write something like this, I need

to be able to give each "card" a random position in the assortment,

and I need the assortment to be different each time the program is

run. (I think) This means I need to be able to generate as many

random numbers at once as the number of "cards" in the assortment when

the program is first loaded. I have tried seeding the rand() function

with GetTickCount() as well as time():

[snip]

Hi Graeme,

might I suggest a simpler alternative.

Just keep getting random numbers until you get the number of random

numbers you need. Performance should be a non-issue in such an app. Ignore

repeated random numbers.

Maybe your method would be okay in this case, but there is something

distasteful about an algorithm that gets slower and slower with each item

chosen. When all but one item has been chosen, it could take hundreds of

calls to rand() before it stumbles across the last one. There are some

pretty simple methods of doing this without any retries. You can have an

array of items and a loop that swaps every item with another, randomly

chosen, item. That guarantees that every item will be in a randomly chosen

position. Or you can choose a randomly chosen item on the fly, which the

following card-dealer does.

class CardDeck

{

enum { NCARDS = 52 };

enum { NSUITS = 4 };

public:

CardDeck()

{

// start with deck in order

for(int icard = 0; icard < NCARDS; ++icard)

{

deck[icard] = icard;

}

// make all cards available

cards_remaining = NCARDS;

}

void Shuffle()

{

cards_remaining = NCARDS;

}

int DealCard()

{

// return error if no cards left

if(cards_remaining == 0)

return -1;

int icard = rand() % cards_remaining;

int card = deck[icard];

deck[icard] = deck[cards_remaining-1];

deck[cards_remaining-1] = card;

--cards_remaining;

return card;

}

private:

int deck[NCARDS];

int cards_remaining;

};

To start with a fresh deck at any time, call Shuffle(). Then each successive

call to DealCard() will return a different card with only one rand() call

needed.

DW