Thursday, April 15, 2010

Random Shuffle

Random shuffling has application in areas like card games. It's highly important that the shuffling is uniform. i.e to say that every possible permutation of the cards should be equally likely. This can be achieved by using uniform random number between 0 an 1. The algorithm (thanks to CLRS) works as follows: at first each 52 cards is equally likely so you select one card and put it in the last position, again of the 51 cards remaining you select another card and so on. At each step each card remaining should be equally likely to be selected. The code below implements the concept.


//random shuffle x elements
void random_shuffle(int x[], int size) {
float r =0;
int new_pos;
for (int j = size -1; j >= 0; j--) {
r = rand()/ (RAND_MAX + 1.0);
new_pos = j * r;
std::swap(x[new_pos], x[j]);
}

//displaying the shuffled elements
std::ostream_iterator iterator(std::cout,"\n");
std::copy(x, x+size, iterator);
}

No comments:

Post a Comment