在我正在开发的游戏中,我有一组表示生物的物体。这些对象(除其他外)具有唯一的标识符和可生成的权重(或概率)。
我正在尝试开发一种随机繁殖生物的算法,但是我没有想出一种使用重量的方法(我真的不知道怎么做)。
有人能帮忙吗?
生物阵列的一个例子可以是:
var creatures = [
{id: 1, weight: 25},
{id: 2, weight: 15},
{id: 3, weight: 5},
{id: 4, weight: 45},
{id: 5, weight: 10}
]发布于 2017-01-01 20:31:47
我在这个博客中找到了这个用PHP实现的好算法,我认为这个算法非常适合您的需要。
我刚把它收养给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);
希望能帮上忙。
发布于 2017-01-01 20:33:15
创建一个新的数组,并将每个生物的id添加到数组中的加权次数。然后获取0与数组大小之间的随机数,并在该位置返回id数。
var creatureIds = [];
for(var i=0;i<creatures.length;i++){
for(var x=0;x<creatures[i].weight;x++){
creatureIds.push(creatures[i].id);
}
}
// get a random index between 0 and the ids length.
var min = 0;
var max = creatureIds.length;
var index = Math.floor(Math.random() * (max - min + 1)) + min;
var randomWeightedCreatureId = creatureIds[index];https://stackoverflow.com/questions/41418689
复制相似问题