模拟人工洗牌。编写一个模拟人工洗牌的程序,讲洗好的牌分别发给四个人。
**输出格式要求:"\nNo.%d:" " %c%2d,"
为便于机器评分,假设随机数的种子为1.即srand(1);然后再调用 rand()函数,即可得到与测试用例相同的随机数序列。
基本思路:
1、先将牌的初始化为:
struct card deck[]={ {1,‘C’},{2,‘C’},{3,‘C’},{4,‘C’},{5,‘C’},{6,‘C’},{7,‘C’}, {8,‘C’},{9,‘C’},{10,‘C’},{11,‘C’},{12,‘C’},{13,‘C’}, {1,‘D’},{2,‘D’},{3,‘D’},{4,‘D’},{5,‘D’},{6,‘D’},{7,‘D’}, {8,‘D’},{9,‘D’},{10,‘D’},{11,‘D’},{12,‘D’},{13,‘D’}, {1,‘H’},{2,‘H’},{3,‘H’},{4,‘H’},{5,‘H’},{6,‘H’},{7,‘H’}, {8,‘H’},{9,‘H’},{10,‘H’},{11,‘H’},{12,‘H’},{13,‘H’}, {1,‘S’},{2,‘S’},{3,‘S’},{4,‘S’},{5,‘S’},{6,‘S’},{7,‘S’}, {8,‘S’},{9,‘S’},{10,‘S’},{11,‘S’},{12,‘S’},{13,‘S’}, };
2、随机选择两张牌(调用rand函数。为便于机器评分,假设随机数的种子为1.即srand(1);然后再调用 rand()函数,即可得到与测试用例相同的随机数序列。)交换两张牌。
3、输出交换52次(洗牌)以后的牌。前13张发给第1个人,然后,再13张发给第2个人,。。。
程序运行结果如下:
No.1: C 9, D10, C10, D 5, D 8, D13, H 5, H 1, C 5, D 7, D 1, C11, No.2: C13, S12, C12, H10, D 2, H 3, S 9, S 6, S 4, S11, C 4, H13, No.3: S10, H12, D 4, S 1, C 7, S 2, S 8, D 3, H 2, D 9, C 2, H11, No.4: S13, C 6, S 5, H 9, S 7, C 3, D12, D11, D 6, H 8, C 1, H 7,
#include <stdio.h> #include <stdlib.h> struct card { int pips; char suit; } ; struct card deck[]={ {1,'C'},{2,'C'},{3,'C'},{4,'C'},{5,'C'},{6,'C'},{7,'C'}, {8,'C'},{9,'C'},{10,'C'},{11,'C'},{12,'C'},{13,'C'}, {1,'D'},{2,'D'},{3,'D'},{4,'D'},{5,'D'},{6,'D'},{7,'D'}, {8,'D'},{9,'D'},{10,'D'},{11,'D'},{12,'D'},{13,'D'}, {1,'H'},{2,'H'},{3,'H'},{4,'H'},{5,'H'},{6,'H'},{7,'H'}, {8,'H'},{9,'H'},{10,'H'},{11,'H'},{12,'H'},{13,'H'}, {1,'S'},{2,'S'},{3,'S'},{4,'S'},{5,'S'},{6,'S'},{7,'S'}, {8,'S'},{9,'S'},{10,'S'},{11,'S'},{12,'S'},{13,'S'}, }; shuffle(deck) struct card deck[]; { int i,j; srand(1); for(i=0;i<52;i++) { j=rand()%52; swapcard(&deck[i],&deck[j]); } } swapcard(p,q) struct card *p,*q; { struct card temp; temp=*p; *p=*q; *q=temp; } main() { int i; shuffle(deck); for(i=0;i<52;i++) if(i%13==0) printf("\nNo.%d:",i/13+1); else printf(" %c%2d,",deck[i].suit,deck[i].pips); }