Roulette Wheel selection
This algorithm is roulette wheel selection with replacement using binary search. Search an item from list will be O(logN) complexity.Overall Complexity O(S)
JavaScript
function object_prop() {
this.p = Math.random(); // access frequency of the object
this.l = Math.random(); // life time of the object
this.s = Math.random(); // size of the object
}
// genrate dummy web objects
function genarate_web_objects(S) {
while (S--) {
objects.push(new object_prop());
}
}
var j = 0;
function select_via_roulette(probability_of_objects, scale) {
var random = Math.random() * scale;
var selected_index = -1;
var first_index = 0;
var last_index = probability_of_objects.length - 1;
var mid_index = parseInt((last_index - first_index) / 2);
while (selected_index < 0 && first_index <= last_index) {
//console.log(mid_index);
if (random < probability_of_objects[mid_index].probability) {
last_index = mid_index;
} else if (random > probability_of_objects[mid_index].probability) {
first_index = mid_index;
}
mid_index = parseInt((first_index + last_index) / 2);
if ((last_index - first_index) == 1)
selected_index = last_index;
//console.log("First",first_index);
// console.log("Second",last_index);
// console.log("Mid",mid_index);
}
// objects_ff.splice(selected_index, 1);
return probability_of_objects[selected_index];
}
function getPrefetchedObjectList(n) {
for (var i = 0; i < S; i++) {
var obj = JSON.parse(JSON.stringify(objects[i]));
obj.fitness = (a * obj.p * obj.l) / (a * obj.p * obj.l + 1);
objects_ff.push(obj);
}
objects_ff.sort(function (a, b) { return a.fitness - b.fitness; });
//console.log("enter", j++);
var sum = objects_ff.reduce(function (sum, b) {
return sum + b.fitness;
}, 0);
var probability_of_objects = [];
//console.log("sum", sum);
var prev_probability = 0;
for (var i = 0; i < objects_ff.length; i++) {
var prob_object = JSON.parse(JSON.stringify(objects_ff[i]));
...