分析:首先54张牌分别用0到53 的数值表示并存储在一个整形数组里,数组下标代表纸牌所在的位置。接下来,遍历整个数组,在遍历过程中随机产生一个随机数,并以该随机数为下标的数组元素与当前遍历到的数组元素进行对换。时间复杂度为O(n) (注:所得到的每一种结果的概率的分母越大越好)
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void shuffle(int boke[]) //洗牌
{
int i,r,t;
srand((unsigned)time(NULL)); //随机数种子
for(i=0; i<54; i++)
{
r=(rand()%107)/2;
//交换
t=boke[i];
boke[i]=boke[r];
boke[r]=t;
}
}
int main()
{
int boke[54],i;
for(i=0;i<54;i++) //初始化纸牌
boke[i]=i;
printf("before shuffle:\n");
for(i=0; i<54; i++) //打印
printf("%d ",boke[i]);
shuffle(boke); //洗牌
printf("\nafter shuffle:\n");
for(i=0; i<54; i++) //打印
printf("%d ",boke[i]);
return 0;
}