2.洗牌程序:用任何语言,随机分配52张扑克牌到52个位置上,每个位置只容许放一张牌
(原题From http://community.csdn.net/Expert/topic/3971/3971377.xml?temp=.7857324)
以下是我的解答。
算法:
纸牌数量 const int COUNT = 52;
用数组AssignAlready[COUNT]存放牌是否分配。如果第i (0 <= i < COUNT)张牌已经分配,那么AssignAlready [i] = 1。数组AssignAlready []的初始值均为0。
数组Poker[COUNT]存放发的牌。
在 0 至 51 中随机取一个整数iIndex,如果iIndex没有发出去,那么将iIndex放到Poker[]中去,如果iIndex发出去了,那么取其后面第一个没有发出去的牌(设定51后面是0)。
void poker(int * const a_iPoker, const int a_iCount)
{
int *AssignAlready = new int[a_iCount];
// Assume none of the cards assigned.
memset(AssignAlready,0,sizeof(int) * a_iCount);
int i;
int iIndex;
//Seed the random-number generator with current time so that
//the numbers will be different every time we run.
srand( (unsigned)time(NULL));
for(i = 0; i < a_iCount; i ++)
{
// get the random index
double dRand = (double)rand() * (a_iCount - 1)/ RAND_MAX;
iIndex = (int)dRand;
while(AssignAlready[iIndex] == 1)
{
iIndex = (iIndex + 1) % a_iCount;
}
a_iPoker[i] = iIndex;
AssignAlready[iIndex] = 1;
}
}
上函数中,
用到了头文件<time.h>。
在main中,输入如下语句:
const int COUNT = 52;
int Poker[COUNT];
poker(Poker,COUNT);
int i;
for (i = 0; i < COUNT ; i ++)
{
cout<< Poker[i] << endl;
}
即可打印出分好的52张牌。
(完毕) ^_^