廣告贊助

[程式語言] C++

[演算法]

Algorithm 洗牌(Shuffling).

針對52張撲克牌洗牌,只需要從第一張牌開始用隨機在52張牌中取得的任一張牌交換,然後繼續第二張牌也是隨機從所有牌中抽出一張作交換,再第三張牌……如此周而復始直到52張牌都與隨機抽出的牌交換過一次,便經過一輪簡單洗牌。

而若是要複雜一點洗牌,則只要多重複第一輪簡單洗牌的過程即可,但可以會耗費程式執行時間與空間。

 [程式架構]

  1. Main() function: 程式入口,要求輸入要發牌的數目,然後顯示發牌結果.
  2. 程式首先必須經過洗牌過程,然後再以迴圈處理每一次發牌並列印出發出的牌面大小。.
  3. 隨機抽出一張牌(隨機選出一個數值)的程式:

#include<ctime>

srand(time(0))  // 用時間作隨機種子,則選出的數比較不會重複。

Int number = rand() % 52 ; //隨機從0-51選出一個數

[程式碼DeckOfCards.cpp

#include <iostream>
#include<ctime>
#include<string>
using namespace std;

const int NUMBER_OF_CARDS = 52;

int main()
{
    cout<<"/**********************************************************"<<endl;
    cout<<"1. Input a number to tell program how many cards you need."<<endl;
    cout<<"2. The Program prints all of cards you get one by one."<<endl;
    cout<<"For Example:"<<endl;
    cout<<"Input a number : 4"<<endl;
    cout<<"You got below cards:"<<endl;
    cout<<"  Spades Ace"<<endl;
    cout<<"  Clubs Queen"<<endl;
    cout<<"  Hearts 5"<<endl;
    cout<<"  Diamonds 2"<<endl;
    cout<<"***********************************************************/"<<endl;
    cout<<endl;
    
    string suits[]={"Spades","Hearts","Clubs","Diamonds"};
    string numbers[]={"Ace","2","3","4","5","6","7","8","9","10","Jack",
                 "Queen","King"};
    int cards[NUMBER_OF_CARDS];
    int n;
    
    for(int i=0; i<NUMBER_OF_CARDS; i++) cards[i] = i;
    
    cout<<"Input a number: ";
    cin>>n;
    cout<<"You got below cards: "<<endl;
    
    //shuffing cards.
    srand(time(0));
    for(int i=0; i<NUMBER_OF_CARDS; i++)
    {
        int swap_index = rand()%NUMBER_OF_CARDS;
        int t = cards[i];
        cards[i] = cards[swap_index];
        cards[swap_index] = t;
    }
    
    //get cards
    for(int i=0;i<n;i++)
    {
        int c = rand()%NUMBER_OF_CARDS; //card
        int cs = c/13;  // card suit 0,1,2,3
        int cg = c%13;  // card number 0,1,2,3,....,12
        
        cout<<"  "<<suits[cs]<<" "<<numbers[cg]<<endl;
    }
    
    cout<<endl;
    system("pause");
    return 0;
}
文章標籤
創作者介紹

儒道哲學的浪漫人生

jackterrylau 發表在 痞客邦 PIXNET 留言(0) 人氣()