Answer the question
In order to leave comments, you need to log in
How to sample by chance?
There is an array of values. It turns out if the value falls below 30 and after adding 30 the output will be "Gold." But what if it should be "Bronze". It turns out everything is repelled from the order in which the elements in the array are located. But if you think logically, shouldn't there be a 50/50 chance between Bronze and Gold, and silver should fall more often. But in my test (Out of 10,000) per turnover, because gold is in first place in the array, it falls more often than bronze.
As a result, my problem is that I do not know how to correctly select an element by chance. In my example, the choice is made by chance AND by position in the array.
There is a simple function with sampling by weight.
var data = [ {name: 'Gold', weight: 30}, {name: 'Silver', weight: 40}, {name: 'Bronze', weight: 30} ];
function GetRandFromArray2(data) {
let total_sum = 0;
for (let i = 0; i < data.length; ++i) {
total_sum += data[i].weight;
}
const rand = Math.floor(Math.random() * total_sum);
total_sum = 0;
for (let i = 0; i < data.length; ++i) {
total_sum += data[i].weight;
if (total_sum >= rand) {
console.log(total_sum, rand)
return [ data[i].weight, data[i].name ];
}
}
}
Answer the question
In order to leave comments, you need to log in
if (total_sum >= rand) {
function getRandom(arr, key) {
const rand = Math.random() * arr.reduce((acc, n) => acc + n[key], 0);
let sum = 0;
return arr.find(n => (sum += n[key]) > rand);
}
const obj = getRandom(data, 'weight');
1. Fill an array with size 100.
2. Get a random value from the array.
For example, fill the array up to 10 with the value 2, from 10 to 40 with the value 1, from 40 to 100 with the value 0.
Here, get the value 2 - 10%, the value 1 - 30%, the value 0 - 60%.
2 - Gold
1 - Silver
0 - Bronze
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question