[C/C++ 演算法]- 洗撲克牌(亂數排列)

[C/C++ 演算法]- 洗撲克牌(亂數排列)

[C/C++ 演算法]- 洗撲克牌(亂數排列)


剛才找資料時發現一個C/C++的教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。

拷貝來源:
http://openhome.cc/Gossip/AlgorithmGossip/
http://openhome.cc/Gossip/AlgorithmGossip/ShuffleCard.htm

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 52

typedef struct {
char suit[3];
char symbol[3];
} Card;
void shuffle(Card*);
void card(int, char*);
void suit(int, char*);
void symbol(int, char*);
int main(void) {
srand(time(0));
Card cards[N];
shuffle(cards);
int i;
for(i = 0; i < N; i++) {
printf("%s%s%c", cards[i].suit, cards[i].symbol,
(i + 1) % 13 ? ' ' : '\n');
}
return 0;
}
void shuffle(Card* cards) {
int i;
for(i = 0; i < N; i++) {
suit(i + 1, cards[i].suit);
symbol(i + 1, cards[i].symbol);
}
for(i = 0; i < N; i++) {
int j = rand() % 52;
Card tmp = cards[i];
cards[i] = cards[j];
cards[j] = tmp;
}
}
void suit(int number, char* suit) {
switch((number - 1) / 13) {
case 0: strcpy(suit, "桃"); break;
case 1: strcpy(suit, "心"); break;
case 2: strcpy(suit, "磚"); break;
case 3: strcpy(suit, "梅");
}
}
void symbol(int number, char* symbol) {
int remain = number % 13;
switch(remain) {
case 0:  sprintf(symbol, "%c ", 'K'); break;
case 1:  sprintf(symbol, "%c ", 'A'); break;
case 11: sprintf(symbol, "%c ", 'J'); break;
case 12: sprintf(symbol, "%c ", 'Q'); break;
default: sprintf(symbol, "%-2d", remain);
}
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *