The Algorithm
Step 1: Initialize the cards. For each i in the [0...n-1] range, set card[i] = i.
Step 2 (optional): Seed the random number generator.
Step 3: Let i = 0.
Step 4: Let j = random_number MOD n.
Step 5: Exchange the values of card[i] and card[j].
Step 6: Let i = i + 1. If i is less than n, go to step 4.
Sample Source Code
Here is a sample C function implementing the algorithm:
void shuffle(int *card, int n) {
int i, j, k;
for (i = 0; i < n; i++)
card[i] = i;
for (i = 0; i < n; i++) {
j = rand() % n;
k = card[i];
card[i] = card[j];
card[j] = k;
}
}
Powered by ScribeFire.
No comments:
Post a Comment