为每个随机对象选择器增加重量



这是我要根据其权重从 liste 随机选择城市的代码,然后根据城市之间的距离修改权重(更多采摘城市的距离会增加重量(。之后,我再次使用修改的Liste 随机选择另一个城市。该代码工作正常,除了一件事...

这是代码:

// list of cities
var liste = [
   { name: "New York", distance: 12, weight: 5, mainweight: 5},
   { name: "Atlanta", distance: 4, weight: 4, mainweight: 4},
   { name: "Dallas", distance: 2, weight: 2, mainweight: 2},
   { name: "Los Angeles", distance: 1, weight: 1, mainweight: 1},
];;
var repeatTimes = 4;
var choose = [];
choose = [liste.map(x=>x.name), liste.map(x=>x.distance), liste.map(x=>x.weight)];
// randomaly pick a city based on its weight
var rand = function(min, max) {
    return Math.random() * (max - min) + min;
};
var getRandomItem = function(choose, weight) {
    var total_weight = weight.reduce(function (prev, cur, i, arr) {
        return prev + cur;
    });
    var random_num = rand(0, total_weight);
    var weight_sum = 0;
    //console.log(random_num)
    for (var i = 0; i < choose.length; i++) {
        weight_sum += weight[i];
        weight_sum = +weight_sum.toFixed(2);
        if (random_num <= weight_sum) {
            return choose[i];
        }
    }
    // end of function, modify the weights of list again
        
};
  // for the first time pick a city randomaly
  var random_item = getRandomItem(choose[0], choose[2]);
  console.log(random_item);
 newWeights();
// after the first time of picking cities let's modify the weights of list
function newWeights(){
var baseDistance = liste.find(l => l.name == random_item).distance;
  
//console.log(liste[choose[0].indexOf(random_item)].distance);
 
var list = liste.map(c => {
  var newWeight = Math.abs(baseDistance - c.distance);
  
    if(newWeight !== 0){
   var newWeight = Math.abs(baseDistance - c.distance) + c.mainweight;
       return {
    name: c.name,
    distance: c.distance,
    weight: newWeight
  };
}
  
  return {
    name: c.name,
    distance: c.distance,
    weight: newWeight
  };
 
});  
liste = list.filter(function(value){
    return value.weight != 0;
});  
choose = [liste.map(x=>x.name), liste.map(x=>x.distance), liste.map(x=>x.weight)];
console.log(liste);
}
// use the modified list to randomaly picking another city
 for (var i = 1; i < repeatTimes; i++) {     
   
       var random_item = getRandomItem(choose[0], choose[2]);
       console.log(random_item);   
        newWeights();
 }

这是我创建列表数组的地方,该数组保存了修改的列表。

var list = liste.map(c => {
  var newWeight = Math.abs(baseDistance - c.distance);
  return {
    name: c.name,
    distance: c.distance,
    weight: newWeight
  };
});

我想要的只是添加每个对象的 strong> newWeater 这样:

if(newWeight !== 0){
var newWeight = Math.abs(baseDistance - c.distance) + c.weight;
}

但是每次我都会出现错误。

if(newWeight !== 0){
   var newWeight = Math.abs(baseDistance - c.distance) + c.weight;
}

在该代码中,您正在检查newWeight,然后初始化newWeight,这可能是您的错误。假设您已经在此代码之前设置了newWeight,请删除var

if(newWeight !== 0){
   newWeight = Math.abs(baseDistance - c.distance) + c.weight;
}

,或者如果您打算将其分配给另一个变量,请更新它以匹配您的含义。

最新更新