// our array of items

var fruits:Array = ['apple','orange','banana','mango'];

// our array of weights

var weights:Array = [20,10,40,30];

// pick a random fruit, based on weights, with bananas most likely to get picked

var 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.

thanks! just what i was looking for!

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

ReplyDeleteThank you very much! Works perfectly!

ReplyDeleteThanks! Just what I needed and it works perfectly.

ReplyDelete