Last active
December 13, 2015 18:18
-
-
Save cduruk/4954064 to your computer and use it in GitHub Desktop.
You meet a man on the street and he says, “I have two children and one is a son born on a Tuesday.” What is the probability that the other child is also a son?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
function getRandomChild() { | |
return { | |
gender: getRandomInt(0, 1), | |
dayOfBirth: getRandomInt(0, 6) | |
} | |
} | |
function getSpecialChild() { | |
return { | |
gender: 0, | |
dayOfBirth: 1 | |
} | |
} | |
function isMale(child) { | |
return child.gender === 0; | |
} | |
function isBornTuesday(child) { | |
return child.dayOfBirth === 1; | |
} | |
// Check if a pair of kids is both male. | |
function isTwoBoys(pair) { | |
var c1 = pair[0]; | |
var c2 = pair[1]; | |
return isMale(c1) && isMale(c2); | |
} | |
// Check in a given pair of kids, one of them is a male born on tuesday | |
// and the other is a boy, born on any day. | |
function isTwoBoysOneBornTuesday(pair) { | |
var c1 = pair[0]; | |
var c2 = pair[1]; | |
var cond1 = isMale(c1) && isBornTuesday(c1) && isMale(c2); | |
var cond2 = isMale(c2) && isBornTuesday(c2) && isMale(c1); | |
return cond1 || cond2; | |
} | |
// Check in a given pair of kids, one of them is a male born on tuesday | |
// and the other is a boy but not born on a tuesday. | |
function isTwoBoysOnlyOneBornTuesday(pair) { | |
var c1 = pair[0]; | |
var c2 = pair[1]; | |
var cond1 = isMale(c1) && !isBornTuesday(c1) && isBornTuesday(c2) && isMale(c2); | |
var cond2 = isMale(c2) && !isBornTuesday(c2) && isBornTuesday(c1) && isMale(c1); | |
return cond1 || cond2; | |
} | |
// Run! | |
var iteration = 1000000; | |
var population = [] | |
// Don't really need this but makes it easier to see population. | |
for (var i = 0; i < iteration; i++) { | |
population.push([getRandomChild(), getSpecialChild()]) | |
} | |
var q1 = q2 = q3 = 0; | |
for (var i=0; i < population.length; i++) { | |
var pair = population[i]; | |
if (isTwoBoys(pair)) { | |
q1++; | |
} | |
if (isTwoBoysOneBornTuesday(pair)) { | |
q2++; | |
} | |
if (isTwoBoysOnlyOneBornTuesday(pair)) { | |
q3++; | |
} | |
} | |
console.log('\nIteration:', iteration); | |
console.log('\nQuestion 1: Two boys\n', q1/iteration); | |
console.log('\nQuestion 2: Two boys, one born on Tuesday\n', q2/iteration); | |
console.log('\nQuestion 2: Two boys, only one born on Tuesday\n', q3/iteration); | |
console.log('\n-- REFERENCE --') | |
console.log('1 / 2:\t\t', 1/2); | |
console.log('13 / 27:\t', 13/27); | |
console.log('12 / 28:\t', 12/28); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment