Tuesday, July 10, 2012

Write a program to shuffle a pack of cards

The approach:-
  1. Initialize a cards array and set the seed for rand based on time.

  2. For each array index generate a random index and swap the elements.

  3. Output the cards array.

C++ program to shuffle a pack of cards

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
int cards[52];
srand(time(0));

for ( int i = 0; i < 52; i++ ) {
   cards[i] = i + 1;
}

for ( int i = 0; i < 52; i++ ) {
   int index = rand() % 52;
   int tmp = cards[i];
   cards[i] = cards[index];
   cards[index] = tmp;
}

for ( int i = 0; i < 52; i++ ) {
   cout << cards[i] << " ";
}
cout << endl;
return 0;
}

Output:-
9 16 21 29 23 37 34 15 47 46 4 27 48 12 39 50 11 36 20 24 6 40 30 7 18 32 14 28 26 8 38 19 51 31 49 44 35 3 41 45 1 13 42 25 2 33 52 5 10 22 43 17

2 comments :

  1. To have an unbiased shuffle, you should use Fisher-Yates shuffle. For each array index, you calculate the random index from the remaining indices, instead of over the whole array size (52).

    http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top