Picking Array Values Using Probability
I have a homework to do, that is: Pick a random color, from yellow, blue and red, given the probability of: Yellow: 3/7 Blue: 1/7 Red: 3/7 I know that I could work this around by
Solution 1:
Instead of a single random value, you create as many as different items you have and later take the one with the max value.
This promotes values/items with a higher factor/probability.
Instead of this approach, you could take a single random value and take all probabilities into an array and check in which interval the random value is. Take this item.
EDIT: The code
function getRandomIndex(probabilities) {
var random = Math.random(),
i;
for (i = 0; i < probabilities.length; i++) {
if (random < probabilities[i]) return i;
random -= probabilities[i];
}
return probabilites.length - 1;
}
var probabilities = [3 / 7, 1 / 7, 3 / 7],
j = 1e6,
count = [0, 0, 0];
while (j--) count[getRandomIndex(probabilities)]++;
console.log(count);
Solution 2:
This is similar to the approach mentioned in the duplicate. You create an array with ratios same as the probabilities. (Here I'm using 2 decimal places and adding ~100 items to the array. You could add multiply by a bigger number and have .toFixed(3)
for better accuracy)
function getRandomWithProbability(array) {
const filled = array.flatMap(([color, prob]) => {
const length = prob.toFixed(2) * 100;
return Array.from({ length }).fill(color)
});
const random = Math.floor(Math.random() * filled.length);
return filled[random]
}
const arr = [["yellow", 3/7], ["blue", 1/7], ["red", 3/7]]
console.log(getRandomWithProbability(arr))
Post a Comment for "Picking Array Values Using Probability"