随笔 - 89  文章 - 118  trackbacks - 0
<2008年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

留言簿(16)

随笔分类(56)

随笔档案(89)

文章分类

推荐博客

搜索

  •  

最新随笔

最新评论

阅读排行榜

转自:http://www.fredosaurus.com/notes-cpp/misc/random-shuffle.html

// File        : misc/random/deal.cpp - Randomly shuffle deck of cards.

// Illustrates : Shuffle algorithm, srand, rand.

// Improvements: Use classes for Card and Deck.

// Author      : Fred Swartz 2003-08-24, shuffle correction 2007-01-18

//               Placed in the public domain.

 

#include <iostream>

#include <cstdlib>   // for srand and rand

#include <ctime>     // for time

using namespace std;

 

int main() {

    int card[52];    // array of cards;

    int n;           // number of cards to deal

    srand(time(0));  // initialize seed "randomly"

    

    for (int i=0; i<52; i++) {

        card[i] = i;  // fill the array in order

    }

   

    while (cin >> n) {   

        //--- Shuffle elements by randomly exchanging each with one other.

        for (int i=0; i<(52-1); i++) {

            int r = i + (rand() % (52-i)); // Random remaining position.

            int temp = card[i]; card[i] = card[r]; card[r] = temp;

        }

       

        //--- Print first n cards as ints.

        for (int c=0; c<n; c++) {

            cout << card[c] << " ";  // Just print number

        }

        cout << endl;

    }

  

   return 0;

}

posted on 2012-12-26 15:59 胡满超 阅读(531) 评论(0)  编辑 收藏 引用 所属分类: 算法转载

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理