I have an array and returning random values.
const array = [ 1, 2 ,3 ,4 ,5, 6, 7, 8]
const rand = array[~~(Math.random() * array.length)]
I would like to return a random element of the array, but with a weighted probability that higher indexes (indices) are less likely to be returned. i.e 8 is less likely to be returned than 1.
How can I achieve this?.
CodePudding user response:
You can use a trick that clones the origin array to a new array by weighted probability.
You can modify it by:
- increase weight on which item you want to show more
- decrease weight on which item you want to show less.
You can check the below demo:
const array = [ 1, 2 ,3 ,4 ,5, 6, 7, 8 ]
const weight = [ 8, 7, 6, 5, 4, 3, 2, 1 ];
let randomArray = [];
array.forEach((item, index) => {
var clone = Array(weight[index]).fill(item);
randomArray.push(...clone);
});
const result = randomArray[~~(Math.random() * randomArray.length)]
console.log('random value:', result);