# C++ Notes: Example - Shuffle Array

Suppose you want to randomize an array of 52 values, from 0 to 51 with no repeats, such as you might want for a deck of cards. First fill the array with the values in order, then go thru the array and exchange each element with a randomly chosen element in the range from itself to the end. It's possible that an element will be exchanged with itself, but there is no problem with that.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 // File : misc/random/deal.cpp - Randomly shuffle deck of cards. // Illustrates : Shuffle algorithm, srand, rand. // Improvements: Use classes for Card and Deck. // Author : Fred Swartz 2003-08-24, shuffle correction 2007-01-18 // Placed in the public domain. #include #include // for srand and rand #include // for time using namespace std; int main() { int card[52]; // array of cards; int n; // number of cards to deal srand(time(0)); // initialize seed "randomly" for (int i=0; i<52; i++) { card[i] = i; // fill the array in order } while (cin >> n) { //--- Shuffle elements by randomly exchanging each with one other. for (int i=0; i<(52-1); i++) { int r = i + (rand() % (52-i)); // Random remaining position. int temp = card[i]; card[i] = card[r]; card[r] = temp; } //--- Print first n cards as ints. for (int c=0; c