Home CPSC 240

Lab 5: Simulation



To get more practice programming with Java classes.



In this lab, you will write some code to solve an old Google interview question that tests candidates reasoning skills. The questions goes like this:

In a country in which people want girls, every family continues to have children until they have a girl. If they have a boy, they have another child. If they have a girl, they stop. What is the proportion of girls to boys 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.


Family Class

You will write a program that solves this puzzle with two classes. The first is the Family class which has the following design:

The rng variable should be marked static (so the objects all share one random number generator. You should assign it equal to a new Random object where it is declared (not the constructor)).

The haveChild method should pick a random number between 0 and 1. It should use that to randomly increment either the girls or boys variable. If it has a girl, it should return true. If it's a boy, false.


Main Class

The second class should be a class which just has a main method. In this main method, do the following things:



When you are done, please submit the two Java files under the assignment in Canvas. Also as a comment, include the outcome and whether you were surprised or not.

Copyright © 2021 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.