// 洗牌算法.cpp : Defines the entry point for the console application.
//
//算法1原理:
/*
1.用一個整型數組記錄各個位置是否已經放置了數,如果放置了則不為0,否則為0。所以在算法開始的時候,初始化此數組每個元素的值都為0.
2.每次產生一個0-53之間的數,看這個位置是否放置了數,如果已經放置了,則繼續采用同樣的方法找一個隨機的位置進行判斷,如果這個位置還未放置,則設置此位置。
3.反復執行步驟2,直到所有的位置都放好了數。
*/
//算法2原理
//先對數組進行初始化,然後隨機交換數組中任意兩個元素。交換的次數越多就越隨機。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle1(int a[],int num)
{
int card,pos;
for(card=1;card<=num;card++)
{
do
{
pos=rand()%(num-1);
} while (a[pos]!=0);
a[pos]=card;
}
}
void shuffle2(int a[],int num)
{
for(int i=1;i<=num;i++)
a[i-1]=i;
int tmp=0,p1,p2;
int cnt=1023;
while (cnt--)
{
p1=rand()%num;
p2=rand()%num;
tmp=a[p1];
a[p1]=a[p2];
a[p2]=tmp;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[54]={0};
int b[54]={0};
clock_t start=clock();
shuffle1(a,54);
clock_t end=clock();
float time=(float)(end-start)/CLOCKS_PER_SEC;
printf("算法1運行時間:%fs\n",time);
start=clock();
shuffle2(b,54);
end=clock();
time=(float)(end-start)/CLOCKS_PER_SEC;
printf("算法2運行時間:%fs\n",time);
for(int i=0;i<54;i++)
{
printf("%d ",a[i]);
}
printf("\n");
for(int i=0;i<54;i++)
{
printf("%d ",b[i]);
}
printf("\n");
system("pause");
return 0;
}