Skip to content

Instantly share code, notes, and snippets.

@7LayersDesign
Last active December 21, 2015 19:58
Show Gist options
  • Save 7LayersDesign/6357477 to your computer and use it in GitHub Desktop.
Save 7LayersDesign/6357477 to your computer and use it in GitHub Desktop.
Weighted random function. Should be used with lists smaller than 100. Passed that is not efficient.
// 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 - 0) + 0);
for (var i = aWeights.length - 1; i >= 0; i--) {sum += aWeights[i]};
if( sum > 100 ) { throw new Exception("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];
};
// Call function example
weightedRandom(items, weights);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment