Skip to content

Instantly share code, notes, and snippets.

@gbezyuk
Created November 10, 2021 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbezyuk/0840c932c596d57370df70b6c3a36114 to your computer and use it in GitHub Desktop.
Save gbezyuk/0840c932c596d57370df70b6c3a36114 to your computer and use it in GitHub Desktop.
function randInt (n) {
return Math.floor(Math.random() * n)
}
function randChoice (array) {
return array[randInt(array.length)]
}
function generateFamily (numberOfKids, possibleGenders) {
const result = []
for (let i = 0; i < numberOfKids; i++) {
result.push(randChoice(possibleGenders))
}
return result
}
function generatePopulation (numberOfFamilies, numberOfKidsPerFamily, possibleGenders) {
const result = []
for (let i = 0; i < numberOfFamilies; i++) {
result.push(generateFamily(numberOfKidsPerFamily, possibleGenders))
}
return result
}
const KIDS_PER_FAMILY = 2
const FAMILIES_TOTAL = 10000
const GENDERS = [ 'male', 'female' ] // we all know there are really only two ;)
const population = generatePopulation(FAMILIES_TOTAL, KIDS_PER_FAMILY, GENDERS)
function familyHasSpecificGenderChild (family, gender) {
return family.includes(gender)
}
function allFamilyChildrenAreSameGender (family, gender) {
return family.filter(c => c === gender).length === family.length
}
const genderToTry = 'male'
const stats = {
totalFamilesTried: 0,
totalFamilesWithMalesTried: 0,
femaleOnlyFamiliesFound: 0,
maleOnlyFamiliesFound: 0,
mixedFamiliesFound: 0,
}
function theTry (population, gender) {
const randomFamily = randChoice(population)
stats.totalFamilesTried++
if (!familyHasSpecificGenderChild(randomFamily, gender)) {
stats.femaleOnlyFamiliesFound++
return
} else {
stats.totalFamilesWithMalesTried++
if (allFamilyChildrenAreSameGender(randomFamily, gender)) {
stats.maleOnlyFamiliesFound++
} else {
stats.mixedFamiliesFound++
}
}
}
const numberOfTries = 5000
for (let i = 0; i < numberOfTries; i++) {
theTry(population, genderToTry)
}
console.log(stats)
console.log('if there is a male child, all are males with probability...', stats.maleOnlyFamiliesFound / stats.totalFamilesWithMalesTried)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment