Skip to content

Instantly share code, notes, and snippets.

@pohatu
Last active December 18, 2015 18:39
Show Gist options
  • Save pohatu/5827442 to your computer and use it in GitHub Desktop.
Save pohatu/5827442 to your computer and use it in GitHub Desktop.
Simulation for Google interview question about having girls until you have a boy
# Problem:
# 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?
$global:m=0; $global:f=0;
function havebabiesuntilboy(){
while($true){
if ((Get-Random -Minimum 0 -Maximum 2) -eq 1)
{
#write-host "boy"
$global:m++; break;
}
else{
#write-host "girl"
$global:f++;
}
}
}
1..100000 | % { havebabiesuntilboy}
# This runs iteratively, but it could run in parallel. It's a simulation so it doesn't matter to the math.
# However, it is a nice simply stated problem that would make a good example for a map/reduce styled solution.
# I leave that as an exercise to the reader.
write-host ("{0:P2}" -f ($m/($f+$m))) "percent male"
write-host ("{0:P2}" -f ($f/($f+$m))) "percent female"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment