KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the range of numbers (0,1,2) choose a number where 0 has an 80% probability of being selected, 1 has a 10% chance and 2 has a 10% chance. It's been about 8 years since my college stats class, so you can imagine the proper formula for this escapes me at the moment. Here's the 'cheap and dirty' method that I came up with. This solution uses ColdFusion. Yours may use whatever language you'd like. I'm a programmer, I think I can handle porting it. Ultimately my solution needs to be in Groovy - I wrote this one in ColdFusion because it's easy to quickly write/test in CF. public function weightedRandom( Struct options ) { var tempArr = []; for( var o in arguments.options ) { var weight = arguments.options[ o ] * 10; for ( var i = 1; i<= weight; i++ ) { arrayAppend( tempArr, o ); } } return tempArr[ randRange( 1, arrayLen( tempArr ) ) ]; } // test it opts = { 0=.8, 1=.1, 2=.1 }; for( x = 1; x<=10; x++ ) { writeDump( weightedRandom( opts ) ); } I'm looking for better solutions, please suggest improvements or alternatives.
Tags (comma-separated)
Save Edits
Cancel