Skip to content

Instantly share code, notes, and snippets.

@SHiLLySiT
Created March 27, 2012 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SHiLLySiT/2221608 to your computer and use it in GitHub Desktop.
Save SHiLLySiT/2221608 to your computer and use it in GitHub Desktop.
Randomly chooses from a set of weighted objects (ints, strings, numbers, etc)
/**
* 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment