Home CPSC 220

Population Simulation



To be able to write simulation programs.


Google used to use an interview question that tested candidates statistics and reasoning skills. The questions goes like this:

In a country in which people only want boys, every family continues to have children until they have a boy. If they have a girl, they have another child. If they have a boy, they stop. What is the proportion of boys to girls in the country?

Before beginning to solve this problem, make a guess as to what the answer is, put this guess in the comments of your program before writing it.



We could solve this problem using statistics, but we can also simulate this hypothetical country and empirically see what will happen.

  1. Create a class called "Family" which contains two private variables: one for the number of boys, and one for the number of girls.
  2. Create a constructor which sets both to 0.
  3. Create "getter" functions which return the number of boys and girls.
  4. Create a function called "step" which will simulate one cycle of the family. If the family already has a boy, the function returns right away. If the family does not have a boy, they have a child. Use a random number generator to decide if they have a boy or girl (it should be 50/50 of course).
  5. In the main function, create and initialize an array of one million families.
  6. Call the "step" function on each until every family has a boy.
  7. Print the number of boys, the number of girls, and the percentage of the population which is male.



When your program works, email the code to ifinlay@umw.edu. Include your conclusion in the body of the email. What is the proportion of boys to girls in this country?

Copyright © 2022 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.