Skip to content

Instantly share code, notes, and snippets.

@7LayersDesign
Last active December 21, 2015 19:58
Show Gist options
  • Save 7LayersDesign/6357503 to your computer and use it in GitHub Desktop.
Save 7LayersDesign/6357503 to your computer and use it in GitHub Desktop.
Test the weightRandom function by calling 1000 times and counting each result.
// array of items. Weight must add up to 100
// video1 = 20%, vieo2 = 50%, video3 = 10%, video4 = 20%
var items = ['Video1', 'Video2', 'Video3', 'Video4'];
var weights = [20, 50, 10, 20];
/**
* Return a random value from aItems based on aWeights
* @param {array} aItems Array of you items.
* @param {array} aWeights Array of weights that match items.
* @return {String} Selected item.
*/
var weightedRandom = function(aItems, aWeights){
var sum = 0;
var rand = Math.floor(Math.random() * 100);
for (var i = aWeights.length - 1; i >= 0; i--) {sum += aWeights[i]};
if( sum > 100 ) { throw new Error("WeightedRandom:WeightsExceed100")};
// Create array with
var weightedList = [];
for (var i = aItems.length - 1; i >= 0; i--) {
for (var x = aWeights[i] - 1; x >= 0; x--) {
weightedList.push(aItems[i]);
};
};
return weightedList[rand];
};
var testRandom = function(iterations, items, weights){
// Create base object to store results.
var results = {};
var item;
for (var i = 0; i < items.length; i++) {
results[items[i]] = 0;
};
// Call weightedRandom iterations times
while( iterations > 0 ){
item = weightedRandom(items, weights);
results[item]++;
iterations--;
}
return results;
};
console.log(testRandom(1000, items, weights));
@7LayersDesign
Copy link
Author

Run code in web dev console to see results of weightedRandom() over 1000 iterations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment