Skip to content

Instantly share code, notes, and snippets.

@highercomve
Last active November 8, 2016 16:20
Show Gist options
  • Select an option

  • Save highercomve/df479129f08af1bfb21553389b2bf101 to your computer and use it in GitHub Desktop.

Select an option

Save highercomve/df479129f08af1bfb21553389b2bf101 to your computer and use it in GitHub Desktop.
// this file is not scope. You must use it inside a anonymus function and save in windows RandomList and RandomList2 or export those
function createWeightedList (list, weight) {
var weighed_list = [];
for (var i = 0; i < weight.length; i++) {
var multiples = weight[i] * 100;
for (var j = 0; j < multiples; j++) {
weighed_list.push(list[i]);
}
}
return weighed_list;
}
function RandomList (list, weight) {
this.weighed_list = createWeightedList(list, weight);
this.length = this.weighed_list.length;
}
RandomList.prototype.next = function () {
return this.weighed_list[Math.floor(Math.random() * this.length)];
}
function RandomList2 (list, weight) {
this.list = list;
this.weight = weight;
this.total_weight = this.weight.reduce(function (prev, cur, i, arr) {
return prev + cur;
});
}
RandomList2.prototype.rand = function rand (min, max) {
return Math.random() * (max - min) + min;
};
RandomList2.prototype.next = function next () {
var random_num = this.rand(0, this.total_weight);
var weight_sum = 0;
for (var i = 0; i < this.list.length; i++) {
weight_sum += this.weight[i];
weight_sum = +weight_sum.toFixed(2);
if (random_num <= weight_sum) {
return this.list[i];
}
}
};
var list = new RandomList(['a', 'b', 'c'], [0.33, 0.33, 0.33]);
var listAnother = new RandomList2(['a', 'b', 'c'], [0.33, 0.33, 0.33]);
function fullCount (listOne, listTwo, until) {
return [count(listOne, until), count(listTwo, until)];
}
function count (list, until) {
var i = 0;
var count = { a: 0, b: 0, c: 0 };
while (i <= until) {
var value = list.next();
if (value === 'a') { count.a += 1; }
else if (value === 'b') { count.b += 1; }
else if (value === 'c') { count.c += 1; }
i++;
}
return count;
}
console.log(fullCount(list, listAnother, 100));
console.log(fullCount(list, listAnother, 100));
console.log(fullCount(list, listAnother, 100));
console.log(fullCount(list, listAnother, 100));
console.log(fullCount(list, listAnother, 100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment