## September 1, 2009

### ActionScript 3: Choose a random item from an Array, with weighting

It's very common to simply choose a random item from an Array, using a random number. But what if we want change the probabilities that certain items will be chosen? I've written a little function that takes an Array of weights (Numbers), which correspond to the Array of items you'd like to choose from, and returns an index to pull a random, weighted item from the source Array. Check out the example:
`// our array of itemsvar fruits:Array = ['apple','orange','banana','mango'];// our array of weightsvar weights:Array = [20,10,40,30];// pick a random fruit, based on weights, with bananas most likely to get pickedvar myFruit:String = fruits[ randomIndexByWeights( weights ) ];/** * Takes an array of weights, and returns a random index based on the weights */private function randomIndexByWeights( weights:Array ) : int{ // add weights var weightsTotal:Number = 0; for( var i:int = 0; i < weights.length; i++ ) weightsTotal += weights[i]; // pick a random number in the total range var rand:Number = Math.random() * weightsTotal; // step through array to find where that would be  weightsTotal = 0; for( i = 0; i < weights.length; i++ ) {  weightsTotal += weights[i];  if( rand < weightsTotal ) return i; } // if random num is exactly = weightsTotal return weights.length - 1;}`

You can see that the weights array must be the same length as the data array that you're choosing from. Note that in the example, my weights add up to 100, but you can use any scale that you'd like, as the weights are added up, and a random number is chosen in that scale.

1. thanks! just what i was looking for!

2. Thanks, was looking for something simple to do this, works perfectly.

3. Thank you very much! Works perfectly!

4. Thanks! Just what I needed and it works perfectly.