一个简单高效的洗牌算法,C代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
* 每次随机抽取一张牌放入数组后部
*/
void shuffle(short *poker, short len) {
int i;
srand((unsigned)time(NULL));
for ( i=len-1; i>=1; i-- ) {
int k = rand()%(i);
int x = poker[k];
poker[k] = poker[i];
poker[i] = x;
}
}
int main(void) {
short LEN = 54, i;
short *poker = malloc(LEN);
for ( i=0; i<LEN; i++ )
poker[i] = i;
shuffle(poker, LEN);
for ( i=0; i<LEN; i++ )
printf("%d ", poker[i]);
free(poker);
return EXIT_SUCCESS;
}