首页 > 其他 > 详细

洗牌算法

时间:2014-05-10 00:59:31      阅读:478      评论:0      收藏:0      [点我收藏+]

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

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

实现1:

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

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

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

bubuko.com,布布扣
/ 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);
                }
            }
        }
    }
}
bubuko.com,布布扣

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

bubuko.com,布布扣
 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]);
            }
        }
    }
bubuko.com,布布扣

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

 

 

 

 

洗牌算法,布布扣,bubuko.com

洗牌算法

原文:http://www.cnblogs.com/limingluzhu/p/3718550.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!