Skip to content

Instantly share code, notes, and snippets.

@tessro
Created November 15, 2009 01:37
Show Gist options
  • Save tessro/234913 to your computer and use it in GitHub Desktop.
Save tessro/234913 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# usage: ./family.rb [trials]
# Family problem, 1000000 trials:
#
# 997496 girls, 1000000 boys
# 1.997496 children per family
# 0.997496 girls per boy
#
# Ran in 15.508096s
class Array
def rand # A spoonful of sugar helps the medicine go down
self[length*Kernel.rand]
end
end
class Family
def initialize(complete = true)
@children = { :boy => 0, :girl => 0 }
complete! if complete
end
def boys
@children[:boy]
end
def girls
@children[:girl]
end
def have_child!
@children[[:boy, :girl].rand] += 1
end
def complete!
have_child! until complete?
end
def complete?
boys == 1
end
end
iterations = if ARGV.length > 0
ARGV[0].to_i
else
1000
end
puts "Family problem, #{iterations} trials:"
started = Time.new
children = { :boys => 0, :girls => 0 }
iterations.times do
f = Family.new
children[:boys] += f.boys
children[:girls] += f.girls
end
family_size = (children[:boys] + children[:girls]).to_f / iterations
ratio = children[:girls].to_f / children[:boys]
elapsed = Time.new - started
puts
puts "#{children[:girls]} girls, #{children[:boys]} boys"
puts "#{family_size} children per family"
puts "#{ratio} girls per boy"
puts
puts "Ran in #{elapsed}s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment