Lab 7: Simulation
Objective
To get more practice programming with Java classes.
Task
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 a class called "Family", which should have the following variables:
- A
Randomvariable which will serve as the random number generator. Mark this as static so that all objects share the same random number generator. You should assign it equal to a new Random object where it is declared (not in the constructor). - An int for the number of girl children.
- An int for the number of boy children.
The class should have the following methods:
- A method called
haveChildrenwhich will produce a child for the family until there is 1 girl. Each time a child is produced, you should pick a random number between 0 and 1. It should use that to randomly increment either the girls or boys variable. - A get method for the number of girls.
- A get method for the number of boys.
Main Class
The second class should be a class which just has a main method. In this main method, do the following things:
- Make an ArrayList of families.
- Add 1 million families to it.
- Go through each family, and call the
haveChildrenmethod on it. This simulates the family having children until they get a girl. - Count all of the boys and girls across all million families.
- Print the numbers out, along with the percentages.
- Was the ratio of boys to girls what you expected? Post the outcome as a comment on the lab when you turn it in.
Submitting
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.