从具有加权元素的数组中获取随机元素 [英] Get random element from array with weighted elements

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

问题描述

我有一组对象代表我正在尝试开发的游戏中的生物.这些对象(除其他外)具有唯一标识符和生成权重(或概率).

I have an array of objects that represent creatures in a game I'm trying to develop. These objects have (among others) a unique identifier and a weight (or probability) to spawn.

我正在尝试开发一种算法来随机生成生物,但我没有想出一种使用权重的方法(我真的不知道该怎么做).

I'm trying to develop an algorithm to spawn creatures randomly but I fail to come up with a way to use the weights (I really don't know how to do it).

有人可以帮忙吗?

生物数组的一个例子可能是:

An example of creatures array could be:

var creatures = [
    {id: 1, weight: 25},
    {id: 2, weight: 15},
    {id: 3, weight: 5},
    {id: 4, weight: 45},
    {id: 5, weight: 10}
]

推荐答案

我在这个 博客 我认为适合您的需求.

I found this nice algorithm implemented in PHP in this blog that I think migth suit your needs.

我刚刚将它采用给 JS.

I just adopted it to JS.

var creatures = [{
    id: 1,
    weight: 25
  }, {
    id: 2,
    weight: 15
  }, {
    id: 3,
    weight: 5
  }, {
    id: 4,
    weight: 45
  }, {
    id: 5,
    weight: 10
  }],
  sumOfWeights = creatures.reduce(function(memo, creature) {
    return memo + creature.weight;
  }, 0),
  selectedWeigths = {};

function getRandom(sumOfWeights) {
  var random = Math.floor(Math.random() * (sumOfWeights + 1));

  return function(creature) {
    random -= creature.weight;
    return random <= 0;
  };
}

for (var i = 0; i < 1000; i++) {
  var creature = creatures.find(getRandom(sumOfWeights));
  selectedWeigths[creature.weight] = (selectedWeigths[creature.weight] || 0) + 1;
}

console.log(selectedWeigths);

希望有帮助.

这篇关于从具有加权元素的数组中获取随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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