Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created March 10, 2012 10:09
Show Gist options
  • Save jonelf/2011028 to your computer and use it in GitHub Desktop.
Save jonelf/2011028 to your computer and use it in GitHub Desktop.
PLaying with conditional probabilities
# You've been told that the Larsson family has four children
# and that three of them are girls. What's that chance that
# the fourth one is also a girl?
# This is a brute force way to settle that.
sibling_count = 4
1.upto(10) do |n|
families = []
# Create a bunch of randomized families
1.upto(sibling_count * 5000) do
family = []
1.upto(sibling_count) do
family << (rand(2) == 0 ? :boy : :girl)
end
families << family
end
# Remove all families with more than 1 boy
families = families.select {|family| family.count {|c| c == :boy} <= 1 }
# Count the number of families with only girls
pure_girl_families = families.count {|family| family.all? {|ch| ch == :girl} }
puts "Study #{n}"
puts "The #{sibling_count}th child is a girl in #{pure_girl_families} families."
puts "Total number of families #{families.length}."
puts "Chance #{pure_girl_families.to_f / families.length}"
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment