Probability Code

Since John Derbyshire has posted code for the probability problem, I thought I'd provide my own, written in C. Typical output is:

Two boys: 2499636 0.249964
One boy, one girl: 4999669 0.499967
Two girls: 2500694 0.250069

Tuesday boys: 714025 0.071402
Their brothers: 357115 0.500144
Their sisters: 356910 0.499856

Enjoy!



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

#define GIRL 1
#define BOY 2
#define TUESDAY 3

/* return a random integer from 1 to max */
int randint(int max)
{
return(1+floor(max*(rand()/(1+(double)RAND_MAX))));
}

int main(void)
{
int N=10000000; /* number of trials */

int n,g[3],d[3],a,b;
int twogirls=0,twoboys=0,boygirl=0;
int tuesdayboys=0,sibgirls=0,sibboys=0;

for (n=1;n<=N;n++)
{
g[1]=randint(2); /* random gender of child 1 (GIRL==1, BOY==2) */
d[1]=randint(7); /* random birth day of child 1 (SUNDAY==1, SATURDAY==7) */

g[2]=randint(2); /* random gender of child 2 */
d[2]=randint(7); /* random birth day of child 2 */

a=randint(2); /* child parent tells you about (1 or 2), chosen at random */
b=3-a; /* child parent tells you nothing about (1 or 2) */

if ((g[a]==BOY)&&(g[b]==BOY)) twoboys++; /* increase count of 2-boy families by one */
if ((g[a]==BOY)&&(g[b]==GIRL)) boygirl++; /* increase count of 1-boy 1-girl families by one */
if ((g[a]==GIRL)&&(g[b]==BOY)) boygirl++; /* increase count of 1-boy 1-girl families by one */
if ((g[a]==GIRL)&&(g[b]==GIRL)) twogirls++; /* increase of 2-girl families by one */

if ((g[a]==BOY)&&(d[a]==TUESDAY)) /* if the child the parent chooses to tell you about is a Tuesday-boy */
{
tuesdayboys++; /* increase count of Tuesday-boys you are told about by one */
if (g[b]==BOY) sibboys++; /* increase count of their brothers by one */
if (g[b]==GIRL) sibgirls++; /* increase count of their sisters by one */
}
}

/* print out counts and ratios */
printf(" Two boys: %d %f\n",twoboys,twoboys/(double)N);
printf("One boy, one girl: %d %f\n",boygirl,boygirl/(double)N);
printf(" Two girls: %d %f\n",twogirls,twogirls/(double)N);
printf("\n");
printf(" Tuesday boys: %d %f\n",tuesdayboys,tuesdayboys/(double)N);
printf(" Their brothers: %d %f\n",sibboys,sibboys/(double)tuesdayboys);
printf(" Their sisters: %d %f\n",sibgirls,sibgirls/(double)tuesdayboys);

return(0);
}

#undef TUESDAY
#undef BOY
#undef GIRL

0 comments: