洗牌程序

2.洗牌程序:用任何语言,随机分配52张扑克牌到52个位置上,每个位置只容许放一张牌

(原题From http://community.csdn.net/Expert/topic/3971/3971377.xml?temp=.7857324

 以下是我的解答。

 

 

 

 

 

算法:

纸牌数量 const int COUNT = 52;

用数组AssignAlready[COUNT]存放牌是否分配。如果第i  (0 <= i < COUNT)张牌已经分配,那么AssignAlready [i] = 1。数组AssignAlready []的初始值均为0

数组Poker[COUNT]存放发的牌。

0 51 中随机取一个整数iIndex,如果iIndex没有发出去,那么将iIndex放到Poker[]中去,如果iIndex发出去了,那么取其后面第一个没有发出去的牌(设定51后面是0)

 

 

 

 

 

 

void poker(int * const a_iPoker, const int a_iCount)

{

    int *AssignAlready = new int[a_iCount];

    // Assume none of the cards assigned.

    memset(AssignAlready,0,sizeof(int) * a_iCount);

 

 

 

 

 

 

    int i;

    int iIndex;

      

       //Seed the random-number generator with current time so that

    //the numbers will be different every time we run.

       srand( (unsigned)time(NULL));

 

 

 

 

 

 

    for(i = 0; i < a_iCount; i ++)

    {

              // get the random index

              double dRand = (double)rand()  * (a_iCount - 1)/ RAND_MAX;

              iIndex = (int)dRand;

       

              while(AssignAlready[iIndex] == 1)

        {

            iIndex = (iIndex + 1) % a_iCount;           

        }

        a_iPoker[i] = iIndex;

        AssignAlready[iIndex] = 1;

    }

}

 

 

 

 

 

 

上函数中,

用到了头文件<time.h>

 

 

 

 

 

 

main中,输入如下语句:
  const int COUNT = 52;

  int Poker[COUNT];

  poker(Poker,COUNT);

  int i;

  for (i = 0; i < COUNT ; i ++)

  {

      cout<< Poker[i] << endl;

  }

 即可打印出分好的52张牌。

(完毕) ^_^

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值