用蒙特卡罗方法验证傻子问题

来源:互联网 发布:seo蜘蛛精有没有用 编辑:程序博客网 时间:2024/04/30 16:48

#include 
<stdlib.h>
#include 
<stdio.h>
#include 
<time.h>

#define uint8 unsigned char
#define MAXSEAT 100
uint8 g_seat[MAXSEAT]
={0};
uint8 g_seattake[MAXSEAT]
={0};


int myrand(int max)
{
    
    
    
return (int)((double)rand() / ((double)RAND_MAX + 1* max+0.5);
}


int Initseat()
{
    
    
int i;
    
int j;
    
int n;
    
int temp;
    
    
    
for (i=0;i<MAXSEAT;i++)
    
{
        g_seat[i]
=i;
    }


    
    
for (j=0;j<10;j++)
    
for (i=0;i<MAXSEAT;i++)
    
{
        n
=myrand(MAXSEAT-1);
        
        temp
=g_seat[i];
        g_seat[i]
=g_seat[n];
        g_seat[n]
=temp;
    }


            
}



void main()
{
    
    
long count;//模拟次数
    long suctimes=0//正确次数
    int i;
    
int n;
    
int j;
    
int k;
    
int temp;
    
int tempn;
    srand( (unsigned)time( NULL ) ); 
//
    
    count
=10000;
    
    
for (i=0;i<count;i++)
    
{
        Initseat();
        
        memset(g_seattake,
0,MAXSEAT);
        n
=myrand(MAXSEAT-1);
        
        g_seattake[n]
=1;
        
if (n==g_seat[0])
        
{
            suctimes
++;
        }

        
else
        
{
            
            
for (j=1;j<MAXSEAT-1;j++)
            
{
                
                
if (g_seattake[g_seat[j]])
                
{
                    
                    temp
=myrand(MAXSEAT-j-1);
                    tempn
=0;
                    
for (k=0;k<MAXSEAT;k++)
                    
{
                        
if (g_seattake[k]==0)
                        
{
                        
                            
if (temp==tempn)
                            
{
                                g_seattake[k]
=1;
                                
break;
                            }

                                tempn
++;
                        }

                        
                    }

                    
                }

                
else
                
{
                    g_seattake[g_seat[j]]
=1;
                }

            }

            
            
if (g_seattake[g_seat[j]]==0)
            
{
                suctimes
++;
            }

        }

        
    }

    
    printf(
"suc=%f,v=%d,n=%d ",100.0*suctimes/count,suctimes,count);
    
}