从网上摘抄的一个洗牌程序的样例:
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
/* one row stores the type, the other one stores the value */
int card[2][52];
int Random(int num)
{
return rand() % num;
}
/*顺序生成一副纸牌,为洗牌做准备啦*/
int Make()
{
int i, j;
for (i = 0; i < 52; i++)
{
card[0][i] = (int)(i / 13) + 3;
card[1][i] = (i) % 13 + 1;
}
return 0;
}
/*显示纸牌*/
int Show()
{
int i, type, value;
char map[] = { 0, 0, 0,'h', 'd', 's', 'b' };
for (i = 0; i < 52; i++)
{
type = card[0][i];
value = card[1][i];
switch (value)
{
case 1:
value = 65;//'A'
break;
case 11:
value = 74;//'J'
break;
case 12:
value = 81;//'Q'
break;
case 13:
value = 75;//'K'
break;
}
if (value < 65)
{
printf("%3c%-4d", map[type], value);
}
else
{
printf("%3c%-4c", map[type], value);
}
if ((i + 1) % 13 == 0) {
printf("\n");
}
}
return 0;
}
/*随机调换纸牌(洗牌过程),参数为调换次数*/
int SwitchCard(int num)
{
int i, tmpType, tmpValue, Postion1, Postion2;
clock_t startTime, endTime;
double dif;
startTime = clock();
puts("正在洗牌 ... ...");
for (i = 0; i < num; i++)
{
Postion1 = Random(52);
Postion2 = Random(52);
tmpType = card[0][Postion1];
tmpValue = card[1][Postion1];
card[0][Postion1] = card[0][Postion2];
card[1][Postion1] = card[1][Postion2];
card[0][Postion2] = tmpType;
card[1][Postion2] = tmpValue;
}
endTime = clock();
// dif = difftime(endTime,startTime);
printf("完成洗牌,交换%d次总耗时:%.3lf\n", num, (double)(endTime - startTime) / CLOCKS_PER_SEC);
return 0;
}
int main(int argc, char* argv[])
{
srand((unsigned)time(NULL));
Make();
Show();
SwitchCard(Random(10000) * Random(1000) + 1);
Show();
return 0;
}
再贴一段我大学时的代码
/* file name: poker.demo.c
* cmd: $gcc poker.demo.c
* author: yilonglucky#gmail.com
* description: a basic demonstration for poker
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define swap(a,b) ((a)^=(b)^=(a)^=(b))
//#define SHUFFLE
#define CARD_NUM 52
#define SUIT_NUM 4
#define RANK_NUM 13
/* card suit */
#if 0
/* ASCII: 3:Heart 4:Diamond 5:Club 6:Spade */
const char suit[]={3, 4, 5, 6};
#else
const char suit[]={'h', 'd', 'c', 's'};
#endif
/* card rank */
const char rank[]={'A','K','Q','J','1','9','8','7','6','5','4','3','2'};
const char ten_pos = 4;
/* 0*13+(0~12) means heart A,K,Q,J ~ 3,2
* 1*13+(0~12) means diamond A,K,Q,J ~ 3,2
* 2*13+(0~12) means club A,K,Q,J ~ 3,2
* 3*13+(0~12) means spade A,K,Q,J ~ 3,2
*/
int main()
{
char card[CARD_NUM];
int i,j;
srand(time(NULL));
/* initialization of all cards */
for(i=0; i<CARD_NUM; i++)
card[i] = i;
#ifdef SHUFFLE
/* shuffle all cards */
for(i = 0; i < CARD_NUM; i++)
{
j = rand() % CARD_NUM;
swap(card[i], card[j]);
}
#endif
/* show the 52 cards */
for(i=0; i < CARD_NUM; i++)
{
/*show the suit and rank*/
printf("%c.%c",suit[card[i]/RANK_NUM], rank[card[i]%RANK_NUM]);
/* need to print "10"*/
if(card[i]%RANK_NUM == ten_pos)
printf("0 ");
else
printf(" ");
if((i+1)%RANK_NUM == 0)
printf("\n");
}
printf("\n");
return 0;
}