Skip to content

Instantly share code, notes, and snippets.

@jacopotarantino
Created December 9, 2019 21:59
Show Gist options
  • Save jacopotarantino/c5f1139310f93be236d7f9e1f591eb76 to your computer and use it in GitHub Desktop.
Save jacopotarantino/c5f1139310f93be236d7f9e1f591eb76 to your computer and use it in GitHub Desktop.
is my die balanced?
// determines number of times you should roll a die to determine if it is "fair"
const find_number_of_rolls = (number_of_sides, required_confidence) => {
const allowed_deviation = 1 - required_confidence
const expected_value_per_side = 1/allowed_deviation
const rolls = expected_value_per_side * number_of_sides
return Math.round(rolls)
}
// rolls array takes the form: value_of_side(int)[]
// this expects that the values per side should be commensurate with required confidence
const is_die_biased = (rolls_array, required_confidence) => {
const allowed_deviation = 1 - required_confidence
const expected_value_per_side = 1/allowed_deviation
const max = Math.round(expected_value_per_side + (expected_value_per_side*allowed_deviation))
const min = Math.round(expected_value_per_side - (expected_value_per_side*allowed_deviation))
return !rolls_array.every((current, index) => {
if(current <= max && current >= min) {
return true
}
else {
console.warn(`die is unbalanced on side ${index+1}`)
return false
}
})
}
const number_of_sides = 20
const required_confidence = 0.8
const rolls_array80correct = [
5,5,4,6,5,
5,5,4,6,5,
5,5,4,6,5,
5,5,4,6,5,
]
const rolls_array90correct = [
9,10,11,9,10,
9,10,11,9,10,
9,10,11,9,10,
9,10,11,9,10,
]
const rolls_array80bad = [
5,5,4,6,5,
5,5,42,6,5,
5,5,4,6,5,
5,5,4,6,5,
]
const rolls_array90bad = [
9,10,11,9,10,
9,10,11,9,10,
9,10,11,1,10,
9,10,11,9,10,
]
console.assert(find_number_of_rolls(20, 0.8) === 100)
console.assert(find_number_of_rolls(20, 0.95) === 400)
console.assert(is_die_biased(rolls_array80correct, 0.8) === false)
console.assert(is_die_biased(rolls_array90correct, 0.9) === false)
console.assert(is_die_biased(rolls_array80bad, 0.8) === true)
console.assert(is_die_biased(rolls_array90bad, 0.9) === true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment