Skip to content

Instantly share code, notes, and snippets.

@gbezyuk
Created November 10, 2021 01:14
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/bc62edd8b9a3c937a772027446fa9b65 to your computer and use it in GitHub Desktop.
Save gbezyuk/bc62edd8b9a3c937a772027446fa9b65 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 allTheSame (array) {
if (!array.length) {
return true
}
return array.filter(v => v === array[0]).length === array.length
}
const boxes = [
[0, 0],
[0, 1],
[1, 1],
]
const valueToTry = 0
const stats = {
totalTries: 0,
totalTriesMatchingValue: 0,
totalInvalidTries: 0,
totalMatches: 0,
totalMismatches: 0,
}
function theTry (boxes, ballColor) {
const randomBox = randChoice(boxes)
stats.totalTries++
const randomBall = randChoice(randomBox)
if (randomBall !== ballColor) {
stats.totalInvalidTries++
return
} else {
stats.totalTriesMatchingValue++
if (allTheSame(randomBox)) {
stats.totalMatches++
} else {
stats.totalMismatches++
}
}
}
const numberOfTries = 5000
for (let i = 0; i < numberOfTries; i++) {
theTry(boxes, valueToTry)
}
console.log(stats)
console.log(stats.totalMatches / stats.totalTriesMatchingValue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment