蒙特卡洛方法模拟随机抽取,这是很基本的手段,不用做什么说明。
在此程序中,作者模拟了1000次,做出了一张概率统计图:横坐标为概率(%),纵坐标为计数
源码
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
enum{number=10000
};
int flag,card[52],num,Na,Nb,Nc,Nd,count;
int chk(double a[4],int n)
{
int i,j,k;
if(n == 1)
{
if(fabs(a[0]-24) < 1e-6) {/*printf("%d %d %d %d \n",a[0],a[1],a[2],a[3]);*//*cout << a[0] << endl; */return 1;}
else
return 0;
}
for(i=0;i<n;i++)
{
for(j = i+1; j< n; j++)
{
double t1 = a[i];
double t2 = a[j];
double b[4];
int r = 0;
for(k = 0; k< n; k++)
{
if((k != i) && (k != j)) b[r++] = a[k];
}
b[n-2] = t1+t2;
if(chk(b,n-1)) return 1;
b[n-2] = t1*t2;
if(chk(b,n-1)) return 1;
b[n-2] = t1-t2;
if(chk(b,n-1)) return 1;
b[n-2] = t2-t1;
if(chk(b,n-1)) return 1;
b[n-2] = t1/t2;
if(chk(b,n-1)) return 1;
b[n-2] = t2/t1;
if(chk(b,n-1)) return 1;
}
}
return 0;
}
int chk24(int a, int b ,int c ,int d)
{
double p[4] = {a,b,c,d};
return chk(p,4);
}
void Random(int i)
{
do
{
Na=rand()%(52-4*i-1+1)+1; /*a为1~(52-4i)之间的随机数*/
Nb=rand()%(52-4*i-1+1)+1; /*a为1~(52-4i)之间的随机数*/
Nc=rand()%(52-4*i-1+1)+1; /*a为1~(52-4i)之间的随机数*/
Nd=rand()%(52-4*i-1+1)+1; /*a为1~(52-4i)之间的随机数*/
}while(!judge());
}
int judge(void)
{
if(Na==Nb||Na==Nc||Na==Nd||Nb==Nc||Nb==Nd||Nc==Nd)
return 0;
else
return 1;
}
int main(void)
{
int a,b,c,d,N=0;
int i,j,k;
double p,sum=0;
srand((unsigned)time(NULL)); /*随机种子*/
for(i=0;i<52;i++)
{
num=i/4+1;
card[i]=num;
}//give value to the card[]
/*for(i=0;i<52;i++)
printf("%d\n",card[i]);*/
for(k=0;k<number;k++)
{
for(i=0;i<13;i++)
{
count=0;//The first card is marked '0'
//srand((unsigned)time(NULL)); /*随机种子*/
Random(i);
//printf("N:%d %d %d %d \n",Na,Nb,Nc,Nd);
for(j=0;j<52;j++)
{
if(card[j]!=0)
count++;//count the rest card
if(count==Na)
a=card[j+1];
else if(count==Nb)
b=card[j+1];
else if(count==Nc)
c=card[j+1];
else if(count==Nd)
d=card[j+1];
//confirm the a,b,c,d
}
//printf("%d %d %d %d \n",a,b,c,d);
count=0;
for(j=0;j<52;j++)
{
if(card[j]!=0)
count++;//count the rest card
if(count==Na)
card[j]=0;
else if(count==Nb)
card[j]=0;
else if(count==Nc)
card[j]=0;
else if(count==Nd)
card[j]=0;
//mark card[j] been taken
}
flag=chk24(a,b,c,d);
if(flag==1)
N++;
//sleep(1);
/*for(j=0;j<52;j++)
printf("%d\n",card[j]);*/
}
p=N/13.0*100;
N=0;
//printf("%f\n",p);
sum+=p;
for(i=0;i<52;i++)
{
num=i/4+1;
card[i]=num;
}//give value to the card[]
}
/*for(i=0;i<52;i++)
printf("%d\n",card[i]);*/
p=sum/number;
printf("\n%f\n",p);
getch();
return 0;
}