Created
August 7, 2018 02:49
-
-
Save maetl/61af61cb8b54620da4fdcabbe2599e6f to your computer and use it in GitHub Desktop.
Pick a weighted value from an object in JS
This file contains 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 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