码迷,mamicode.com
首页 > 编程语言 > 详细

(算法)完美洗牌

时间:2015-10-21 23:55:01      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

题目:

编写一个方法,洗一副牌,要求做到完美洗牌,即这副牌52!中排列组合出现的概率相同。

思路:

1、递归

2、循环

代码:

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

int rnd(int lower,int higher){
    return rand()%(higher-lower+1)+lower;
}

void shuffle_1(int *cards,int n){
    if(n==1)
        return;

    shuffle_1(cards,n-1);

    int k=rnd(0,n-1);

    int tmp=cards[k];
    cards[k]=cards[n-1];
    cards[n-1]=tmp;
}

void shuffle_2(int *cards,int n){
    for(int i=0;i<n;i++){
        int k=rnd(0,i);
        int tmp=cards[k];
        cards[k]=cards[i];
        cards[i]=tmp;
    }    
}

int main(){
    srand((unsigned)time(0));
    int cards[52];
    for(int i=0;i<52;i++)
        cards[i]=i+1;
    shuffle_1(cards,52);
    shuffle_2(cards,52);
    return 0;    
}

 

(算法)完美洗牌

标签:

原文地址:http://www.cnblogs.com/AndyJee/p/4899318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!