public
Created

Randomly chooses from a set of weighted objects (ints, strings, numbers, etc)

  • Download Gist
weightedChoice
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
* Randomly chooses from a set of weighted objects (ints, strings, numbers, etc)
* @param objs The objects to choose from.
* @param objWeights The weight of each respective object.
* @return The randomly chosen value.
*/
public static function weightedChoice(objs:Array, objWeights:Array):*
{
var weighedObjs:Array = new Array(); //new array to hold "weighted" obj
var currentObj:int = 0;
while (currentObj < objs.length) { //step through each obj[] element
for (var i:uint = 0; i < objWeights[currentObj]; i++) {
weighedObjs[weighedObjs.length] = objs[currentObj];
}
currentObj++;
}
return FP.choose(weighedObjs);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.