龙空技术网

碎片时间学编程「272]:从数组中获取一个随机元素每个元素的概率

路条编程 54

前言:

此时咱们对“c语言数组赋随机值”大致比较重视,同学们都想要了解一些“c语言数组赋随机值”的相关文章。那么小编在网上网罗了一些对于“c语言数组赋随机值””的相关文章,希望同学们能喜欢,看官们快快来了解一下吧!

从数组中获取一个随机元素,使用提供的 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

更多内容请访问我的网站:

标签: #c语言数组赋随机值