加权概率随机选择数组 [英] Weighted probability random choice array

查看:36
本文介绍了加权概率随机选择数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组并返回随机值.

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)]

我想返回数组的一个随机元素,但有一个加权概率,即返回较高索引(索引)的可能性较小.即 8 比 1 更不可能被返回.

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?.

推荐答案

您可以使用一种技巧,通过加权概率将原始数组克隆为新数组.

You can use a trick that clones the origin array to a new array by weighted probability.

您可以通过以下方式对其进行修改:

You can modify it by:

  • 增加要显示更多项目的权重
  • 降低您希望少显示的项目的权重.

您可以查看以下演示:

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);

这篇关于加权概率随机选择数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆