#!/usr/bin/perl

#
# Royal Family Simulation
# A royal family has children until it has a boy or until it has three
# children, whichever comes first. Assume that each child is a girl (or
# boy) with probability 1/2. Find the expected number of boys and the
# expected number of girls in this royal family. 
#
# This simulation adds the number of boys and girls from $t families
# and prints the result of all the families.
#


$t = 10000;			# Total number of families

for($i = 0; $i < $t; $i++) {
  $c = 0;			# Number of children at the moment
  $b = 0; $g = 0;		# Boys and girls in the family
  until($c == 3) {
    if(rand(1) < 0.5) {	# 50-50 chance
      $b++;		# Having a boy
      $c = 3;		# Set t to be 3 so no more children are born
    } else {
      $g++;		# Having a girl
      $c++;		# Add one to c, the number of children
    }
  }
  $tb += $b;
  $tg += $g;
}

print "Altogether these $t families have $tb boy(s) and $tg girl(s)\n";

