Skip to content

Instantly share code, notes, and snippets.

@maetl
Created August 7, 2018 02:49
Show Gist options
  • Save maetl/61af61cb8b54620da4fdcabbe2599e6f to your computer and use it in GitHub Desktop.
Save maetl/61af61cb8b54620da4fdcabbe2599e6f to your computer and use it in GitHub Desktop.
Pick a weighted value from an object in JS
const rules = {
'90%': 0.9,
'10%': 0.1
}
function pickWeightedValue(rules) {
const productions = Object.keys(rules)
const weights = Object.values(rules)
let maxIndex = 0
let maxWeight = 0
let maxRoll = 0
for (let i=0; i<weights.length; i++) {
let currentWeight = weights[i]
let currentRoll = Math.pow(Math.random(), 1.0 / currentWeight)
if (currentRoll > maxRoll) {
maxRoll = currentRoll
maxWeight = currentWeight
maxIndex = i
}
}
return productions[maxIndex]
}
const buckets = { '90%': 0, '10%': 0 }
for (z=0; z<1000; z++) {
let result = pickWeightedValue(rules)
buckets[result] = buckets[result] + 1
}
console.log(buckets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment