碎片时间学编程「272]:从数组中获取一个随机元素,使用提供的 weights 作为每个元素

从数组中获取一个随机元素,使用提供的 weights 作为每个元素的概率
使用 Array.prototype.reduce() 方法为 weights中的每个值创建一个数组。
使用 Math.random() 方法生成随机数并用 Array.prototype.findIndex() 方法根据先前生成的数组找到正确的索引。
最后,返回带有生成索引的 arr 元素。
JavaScript
const weightedSample = (arr, weights) => {
let roll = Math.random();
return arr[
weights
.reduce(
(acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]),
[]
)
.findIndex((v, i, s) => roll >= (i === 0 ? 0 : s[i - 1]) && roll < v)
];
};
示例:
weightedSample([3, 7, 9, 11], [0.1, 0.2, 0.6, 0.1]); // 9
更多内容请访问我的网站:https://www.icoderoad.com