c语言扑克洗牌

重新写的程序。每次洗出一张,放在最后,剩下的牌重新洗,直至最后一张。代码如下:

 

#include<stdio.h>
#include<time.h>
int N=54;
char * pk[]={"黑桃A","黑桃2","黑桃3","黑桃4","黑桃5","黑桃6","黑桃7","黑桃8","黑桃9","黑桃10","黑桃J","黑桃Q","黑桃K","红桃A","红桃2","红桃3","红桃4","红桃5","红桃6","红桃7","红桃8","红桃9","红桃10","红桃J","红桃Q","红桃K","草花A","草花2","草花3","草花4","草花5","草花6","草花7","草花8","草花9","草花10","草花J","草花Q","草花K","方块A","方块2","方块3","方块4","方块5","方块6","方块7","方块8","方块9","方块10","方块J","方块Q","方块K","大王","小王"};
main()
{
	int a[N];

	int i;
	int temp;
	int p;
	int ten=0;
	unsigned int time1,time2;
	int m=0;
	for (i=0;i<N;i++)
	{
		a[i]=i;
	}

	srand((unsigned)time(NULL));
	for (m=0;m<100000;m++){
	for (i=N-1;i>0;i--)
	{		
		temp= rand() % i;
		p=a[i];
		a[i]=a[temp];
		a[temp]=p;
	}}

	for (i=0;i<N;i++)
	{
		printf("%02d:%-5s  ",i+1,pk[a[i]]);
		ten++;
		if (ten==10)
		{
			printf("\n");
			ten=0;
		}
	}
	printf("\n");

}

 

 

贴图:

c语言扑克洗牌算法

c语言之洗牌算法

在火车上看人打扑克,想做个洗牌算法。我的思路用c语言实现,是这样的:

 

/*本程序是洗牌算法的c语言实现.
原理是,生成52个随机数;每生成一个,记录在数组中,同时记下该数已经生成.下次再生成随机数,如果
已经成生过,则重新生成一个随机数.生成与否,该信息记录在另一个数组中.例如,如果数字15已经成生,则
array[15]=1;

*/

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define  N 52
int poker[N];   //用来记录生成的扑克代码
int back[N];    //用来记录"hash"信息

init_back()
{
//初始化hash数组
	int i=0;
	for (i=0;i<N;i++)
	{
		back[i]=0;
	}
	
}

//辅助函数,用来打印数组,每10个一行.
print_array(int * array)
{
	int i=0,m=0;
	
	for (i=0;i<N;i++)
	{		
		printf("%d ",array[i]);
		if ((i+1) % 10 ==0 && i)
		{
			printf("\n");
		}
	}   
	printf("\n");  
}

//生成随机数.
rand_back()
{
	int i=0;
	int counter=0;                      //用来测试一共生成了多少次随机数.计算效率.
    srand((unsigned)time(   NULL   )   );//用来初始化随机函数,以便生成不同的随机数.
	for (i=0;i<N;i++)
	{
	    ++counter;
		int p=rand()%N;
		if (!back[p])
		{
			poker[i]=p;
			back[p]=1;
		}
		else
		{
		i--;		
		}		
	}
	printf("the counter is: %d\t,效率是 %f;\n",counter,(52.0/counter));
	
}

int main()
{
	//print_array(poker);
	init_back();
	rand_back();
	//print_array(poker);
	//getchar();

}

生成其中一组随机记录为:

23 8 5 17 48 51 14 49 35 36
38 30 31 24 29 47 34 18 41 11
27 16 26 9 45 43 46 0 3 19
37 13 32 20 6 22 4 33 7 21
40 50 42 1 2 28 39 15 25 12
10 44

不过效率似乎不高。计算所生成的有效随机数与尝试次数之比,结果如下:

c语言之洗牌算法