Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created February 11, 2012 02:12
Show Gist options
  • Save jeffreyiacono/1795375 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1795375 to your computer and use it in GitHub Desktop.
simulation of the math 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 gir
# simulation to calculate an answer to the question:
#
# "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?"
#
# !/usr/bin/env ruby
# usage: ./family-sim.rb [trials]
#
# sample output:
#
# $> ./family-sim.rb 1000000
# Family problem, 1000000 trials:
#
# 999471 girls, 1000000 boys
# 1.999471 children per family
# 0.999471 girls per boy
#
# Ran in 7.445696s
class Family
def initialize
@children = {:boy => 0, :girl => 0}
end
def boys
@children[:boy]
end
def girls
@children[:girl]
end
def have_child!
@children[[:boy, :girl].sample] += 1
end
def has_boy?
boys == 1
end
end
# read from standard input or default to 1000 iterations
iterations = if ARGV.length > 0
ARGV[0].to_i
else
1000
end
puts "Family problem, #{iterations} trials:"
started = Time.new
results = {:boys => 0, :girls => 0}
iterations.times do
family = Family.new
family.have_child! until family.has_boy?
results[:boys] += family.boys
results[:girls] += family.girls
end
family_size = (results[:boys] + results[:girls]).to_f / iterations
ratio = results[:girls].to_f / results[:boys]
runtime = Time.new - started
puts
puts "#{results[:girls]} girls, #{results[:boys]} boys"
puts "#{family_size} children per family"
puts "#{ratio} girls per boy"
puts
puts "Ran in #{runtime}s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment