Created
May 22, 2024 23:56
-
-
Save zisra/0aafed2f445257f1a46c6807b1552a67 to your computer and use it in GitHub Desktop.
Pig game
This file contains hidden or 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
const ITERATIONS_USED = 10_000; | |
const MAX_LIMIT = 10; | |
const DICE_FACES = 6; | |
const MAX_DIGITS = 4; | |
function rollDice() { | |
return Math.floor(1 + Math.random() * DICE_FACES); | |
} | |
function rollDiceUntilBreak(limit) { | |
let diceRolls = 0; | |
let total = 0; | |
while (diceRolls < limit) { | |
const result = rollDice(); | |
diceRolls++; | |
if (result === 1) { | |
return 0; | |
} else { | |
total += result; | |
} | |
} | |
return total; | |
} | |
function burstRounds(limit, iterations) { | |
let total = 0; | |
for (let i = 0; i < iterations; i++) { | |
const result = rollDiceUntilBreak(limit); | |
total += result; | |
} | |
return total / iterations; | |
} | |
function predictAverage(limit) { | |
return Math.pow(5 / 6, limit) * (limit * 4); | |
} | |
function stripDigits(number) { | |
return parseFloat(number).toFixed(MAX_DIGITS); | |
} | |
for (let limit = 1; limit < MAX_LIMIT; limit++) { | |
const average = stripDigits(burstRounds(limit, ITERATIONS_USED)); | |
const predicted = stripDigits(predictAverage(limit)); | |
console.log( | |
`For dice rolled ${limit} times, the average score is: ${stripDigits( | |
average | |
)}, while the predicted average is: ${stripDigits( | |
predicted | |
)}, with a difference of: ${stripDigits(average - predicted)}` | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment