伪随机数及避免重复的方法

伪随机数实现

#include 
#include 
#include 
#include 
class TRandom
{
public:
    TRandom(long seed=0){mSeed=(seed?seed:GetTickCount());}
    void Seed(long seed=0)  { mSeed=(seed?seed: GetTickCount( )); }
    int  Integer()                { return Next();}
    int  Integer(int min,int max) { return min+Next()%(max-min+1);}
    double Real()               {return double(Next())/double(INT_MAX);}
private:
    void Change()       {mSeed=(314159265*mSeed+13579)%ULONG_MAX;}
    int  Next() {
                int loops=mSeed%3;
                for (int i=0;i<=loops;i++)
                    Change ();
        return int(mSeed/2);
            }
    unsigned long  mSeed;
};

避免重复的使用方法

法一
洗牌例子:

#include"TRandom.h"
#include
using namespace std;
int main()
{
    int poker[54],i,j;
    TRandom t;
    for (i=0;i<54;i++)
    {
        poker[i]=t.Integer(0,53);
        int flag=1;                     //增加了flag结合while避免出现重复数
        while(flag==1)
        {
            for(j=0;j

法二

#include "TRandom.h"
#include
int main()
{
        int cards[54];
    for(int i=0;i<54;++i)
        cards[i]=i+1;
        TRandom rand;   //创建伪随机数发生器的一个实例对象
  //以下是洗牌过程
         for(int j=0;j<54;++j) {
          int pos=rand.Integer(j,53); //pos是一个[j,53]之间的随机数
                  //交换cards[j]和cards[pos];
                  int temp=cards[j];
                  cards[j]=cards[pos];
                   cards[pos]=temp;
       }
//输出洗牌结果
         for (int k=0;k<54;++k)
                    cout<<"Cards["<

你可能感兴趣的:(伪随机数及避免重复的方法)