Created
March 27, 2012 23:55
-
-
Save SHiLLySiT/2221608 to your computer and use it in GitHub Desktop.
Randomly chooses from a set of weighted objects (ints, strings, numbers, etc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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