- Timestamp:
- Apr 16, 2021, 9:02:58 AM (3 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
ps/trunk/binaries/data/mods/public/simulation/helpers/WeightedList.js
r19270 r25276 1 var WeightedList = function()1 () 2 2 { 3 this.elements = [ ];4 3 ; 4 this.totalWeight = 0; 5 5 }; 6 6 7 7 WeightedList.prototype.length = function() 8 8 { 9 return this.elements. length;9 return this.elements.; 10 10 }; 11 11 12 WeightedList.prototype.push = function(item, weight )12 WeightedList.prototype.push = function(item, weight) 13 13 { 14 if (weight === undefined) 15 weight = 1; 14 this.elements.set(item, weight); 16 15 this.totalWeight += weight; 17 this.elements.push({ "item": item, "weight": weight });18 16 }; 19 17 20 WeightedList.prototype.remove At = function(index)18 WeightedList.prototype.remove) 21 19 { 22 var element = this.elements.splice(index, 1)[0]; 23 if (element) 24 this.totalWeight -= element.weight; 20 const weight = this.elements.get(item); 21 if (weight) 22 this.totalWeight -= weight; 23 this.elements.delete(item); 25 24 }; 26 25 27 WeightedList.prototype. itemAt = function(index)26 WeightedList.prototype.) 28 27 { 29 var element = this.elements[index]; 30 return element ? element.item : null; 31 }; 32 33 WeightedList.prototype.randomIndex = function() { 34 var element; 35 var targetWeight = randFloat(0, this.totalWeight); 36 var cumulativeWeight = 0; 37 for (var index = 0; index < this.elements.length; index++) 28 const targetWeight = randFloat(0, this.totalWeight); 29 let cumulativeWeight = 0; 30 for (let [item, weight] of this.elements) 38 31 { 39 element = this.elements[index]; 40 cumulativeWeight += element.weight; 32 cumulativeWeight += weight; 41 33 if (cumulativeWeight >= targetWeight) 42 return i ndex;34 return i; 43 35 } 44 return -1;36 return ; 45 37 }; 46 38
Note:
See TracChangeset
for help on using the changeset viewer.