**Write a method to shuffle a deck of cards. It must be a perfect shuffle–in other words, each of the 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.**

C++:

01 int random(int m)

02 {

03 return rand()%m;

04 }

05

06 void shuffle(int card[])

07 {

08 int index;

09 for(int i=0;i<50;i++){

10 index=random(52–i);

11 index+=i;

12 int tmp=card[i];

13 card[i]=card[index];

14 card[index]=tmp;

15 }

16 }

02 {

03 return rand()%m;

04 }

05

06 void shuffle(int card[])

07 {

08 int index;

09 for(int i=0;i<50;i++){

10 index=random(52–i);

11 index+=i;

12 int tmp=card[i];

13 card[i]=card[index];

14 card[index]=tmp;

15 }

16 }

Advertisements