random_shuffle演算法小例子

xringm發表於2016-03-28

原文地址:http://blog.csdn.net/aheroofeast/article/details/3907192

首先簡單的介紹一個撲克牌洗牌的方法,假設一個陣列 poker[52] 中存有一副撲克牌1-52的牌點值,使用一個for迴圈遍歷這個陣列,每次迴圈都生成一個[0,52)之間的隨機數RandNum,以RandNum為陣列下標,把當前下標對應的值和RandNum對應位置的值交換,迴圈結束,每個牌都與某個位置交換了一次,這樣一副牌就被打亂了。

  1. for (int i = 0; i < 52; ++i)  
  2. {  
  3.     int RandNum = rand() % 52;  
  4.   
  5.     int tmp = poker[i];  
  6.     poker[i] = poker[RandNum];  
  7.     poker[RandNum] = tmp;  
  8. }  
  

random_shuffle 的第三個引數,需要的是一個函式物件, 這個函式物件的引數是演算法遍歷序列時的index,返回值是0-X 之間的一個隨機數,這個 X 可由使用者來決定。預設的random_shuffle中, 被操作序列的index 與 rand() % N 兩個位置的值交換,來達到亂序的目的。

 

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <vector>  
  4. #include <ctime>  
  5. #include <cstdlib>  
  6.   
  7. using namespace std;  
  8.   
  9. const int POKER_NUM = 52; //52張撲克牌  
  10.   
  11. void print_poker(int PokerNum)  
  12. {  
  13.     cout << PokerNum << " ";  
  14. }  
  15.   
  16. class MyRand  
  17. {      
  18. public:  
  19.     int operator()(int index)  
  20.     {  
  21.         return rand() % POKER_NUM;  
  22.     }  
  23. };  
  24.   
  25. int main()  
  26. {  
  27.     srand( (unsigned)time(NULL) ); //設定隨即數生成器的種子  
  28.   
  29.     vector<int> poker; //一副牌,牌點數從 1 計  
  30.   
  31.     //初始化  
  32.     for (int num = 0; num < POKER_NUM; ++num)  
  33.     {  
  34.         poker.push_back(num+1);  
  35.     }  
  36.   
  37.     //用預設隨機數洗一遍  
  38.     random_shuffle(poker.begin(), poker.end());  
  39.     for_each(poker.begin(), poker.end(), print_poker);  
  40.     cout << endl;  
  41.   
  42.     //用自定義隨機數再洗一遍  
  43.     random_shuffle(poker.begin(), poker.end(), MyRand());  
  44.     copy(poker.begin(), poker.end(), ostream_iterator<int>(cout, " "));  
  45.     cout << endl;      

相關文章