2010-11-02 114 views
12

我正在爲C++程序製作一個Deck類。它需要兩種方法:一種是從甲板頂部彈出一張牌,另一種是洗牌。我很關心後者。洗牌一套

卡被表示爲整數1至52(含)。什麼是最快的算法來洗牌(假設「好」的隨機性水平)?

回答

26

如果您希望自己實施shuffle,可以使用一個非常簡單但功能強大的混洗算法:Fisher–Yates shuffle

要隨機陣列的n個元素:

for i from n − 1 downto 1 do 
    j ← random integer with 0 ≤ j ≤ i 
    exchange a[j] and a[i] 

當然,C++標準庫還具有這樣的事情對於您實現,諸如std::random_shuffle,經由<algorithm>頭包括在內。

+0

(順便說一句,我相當肯定,該標準實施的'的std :: random_shuffle' * *是一個費雪耶茨洗牌。) – Amber 2010-11-02 06:46:30

+1

洗牌容易**一旦**你知道該怎麼做。如果你沒有在數學課上研究隨機性,那麼很容易弄錯它。 – 2010-11-02 08:18:24

+0

@Martin:如果你不能遵循簡單的指令很容易出錯; -p – 2010-11-02 09:37:46

8

使用std::random_shuffle洗牌。

0

這裏是我的代碼

#include<stdlib.h> 
#include<iostream> 
using namespace std; 
int b[52],count=0; 
int check(int k) 
{  int i=0; 
    while(b[i++]!=-1) 
    { 
    if(b[i]==k) 

> Blockquote 

    return 0;} 
    b[count++]=k; 
    cout<<k<<endl; 
    return 1; 

} 
void random(int a[]) 
{ 

    int i=0,p=0,k=0; 
    for(i=1;i<52;i++) 
    { srand(rand()%9); 
    k=0; 
     while(!k) 
     { 
    p=rand()%52; 
    k=check(p); 
     } 
    } 

} 
int main() 
{ 
    int n=52,i=0,arr[n]; 
    for(i=0;i<52;i++) 
    {arr[i]=i;b[i]=-1; } 
    random(arr); 
}