首页 > 代码库 > 洗牌算法

洗牌算法

题目:实现52张牌的随机发放,用户数目为3

思路:使用随机函数实现。

实现1:

生成随机数,后面生成的数需要和前面的数字进行比较,如果发现前面已经生成,就重新再生成。直至生成的总数为52

使用二维数组用来标示牌的花数和牌上的数字,card[4][13]

其中第二维标示花数,第一维标示数字

/ poker.cpp : Defines the entry point for the console application.
 //

#include "stdafx.h"

#include <stdlib.h>
#include <time.h>

void shuffle(int wDeck[4][13]);
void deal(int wDeck[4][13], char*wFace[13], char*wSuit[4]);

void main()
{
  char*wSuit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};
  char*wFace[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
  "Nine", "Ten", "Jack", "Queen", "King"};
   int wDeck[4][13] = {0};

    srand(time(NULL));

    shuffle(wDeck);
    deal(wDeck, wFace, wSuit);

    system("PAUSE");
}

void shuffle(int wDeck[4][13])
{
int r;
int card, row, column;

for(card =1; card <=52; card ++)
    {
        r = rand();
        row = r%4;
        r = rand();
        column = r%13;

while(wDeck[row][column] !=0)
        {
            r = rand();
            row = r%4;
            r = rand();
            column = r%13;
        }

        wDeck[row][column] = card;
    }
}

void deal(int wDeck[4][13], char*wFace[13], char*wSuit[4])
{
char c;
int card, row, column;
    
for (card =1; card <=52; card ++)
    {
for (row =0; row <=3; row ++)
        {
for(column =0; column <=12; column ++)
            {
if (wDeck[row][column] == card)
                {
if (card %3==0)
                    {
                        c =\n;
                    } 
else
                    {
                        c =\t;
                    }
                    printf("%5s of %-8s%c", wFace[column], wSuit[row], c);
                }
            }
        }
    }
}

2.参考java.util.Collections类中的Shuffle实现过程

 public static void shuffle(List<?> list, Random rnd) {
        int size = list.size();
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
            for (int i=size; i>1; i--)
                swap(list, i-1, rnd.nextInt(i));
        } else {
            Object arr[] = list.toArray();

            // Shuffle array
            for (int i=size; i>1; i--)
                swap(arr, i-1, rnd.nextInt(i));

            // Dump array back into list
            ListIterator it = list.listIterator();
            for (int i=0; i<arr.length; i++) {
                it.next();
                it.set(arr[i]);
            }
        }
    }

思路:生成当前数字前的随机数值,然后将当前数字和随机值进行交换,直至到第一个数字