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.
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:
Random
variable 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).The class should have the following methods:
haveChildren
which 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.The second class should be a class which just has a main method. In this main method, do the following things:
haveChildren
method
on it. This simulates the family having children until they get a girl.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.
A solution to this lab can be found in Family.java, and Main.java.
Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.